// LoginGate — wraps the app. On mount, calls /api/auth/me. If unauthenticated,
// renders a centered email/password form. After successful login, renders the
// children (the full Atelier app). Used in Zen Color.html before <App/>.
//
// Future flexibility: when we add Google OAuth (or other providers), this
// component just gets a "Sign in with Google" button below the form — the
// rest of the app stays unaware of how auth was obtained.

function LoginGate({ children }) {
  const [state, setState] = React.useState({ kind: 'loading' });
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);

  const refresh = React.useCallback(async () => {
    try {
      const r = await fetch('/api/auth/me', { credentials: 'same-origin' });
      if (r.ok) {
        const j = await r.json();
        setState({ kind: 'authed', user: j.user });
      } else {
        setState({ kind: 'anon' });
      }
    } catch {
      setState({ kind: 'anon' });
    }
  }, []);

  React.useEffect(() => { refresh(); }, [refresh]);

  const onSubmit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setSubmitting(true);
    setError(null);
    try {
      const r = await fetch('/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
        credentials: 'same-origin',
      });
      if (!r.ok) {
        const j = await r.json().catch(() => ({}));
        throw new Error(j.error || 'login failed');
      }
      const j = await r.json();
      setState({ kind: 'authed', user: j.user });
      setPassword('');
    } catch (err) {
      setError(String(err.message || err));
    } finally {
      setSubmitting(false);
    }
  };

  const logout = async () => {
    await fetch('/api/auth/logout', { method: 'POST', credentials: 'same-origin' });
    setState({ kind: 'anon' });
  };

  if (state.kind === 'loading') {
    return (
      <div style={loginStyles.center}>
        <div style={loginStyles.spinner}>·</div>
      </div>
    );
  }

  if (state.kind === 'anon') {
    return (
      <div style={loginStyles.center}>
        <form onSubmit={onSubmit} style={loginStyles.card}>
          <div style={loginStyles.brand}>
            <svg viewBox="0 0 24 24" width={36} height={36}>
              <circle cx={12} cy={12} r={10} fill="none" stroke="#1a1a1a" strokeWidth={1} />
              <circle cx={12} cy={12} r={5} fill="#1a1a1a" />
            </svg>
            <div style={loginStyles.brandName}>Zen Color</div>
            <div style={loginStyles.brandSub}>meditative coloring · v{(typeof window !== 'undefined' && window.__zenAppVersion) || '?'}</div>
          </div>
          <label style={loginStyles.label}>
            <span style={loginStyles.labelText}>USERNAME</span>
            <input
              type="text" autoComplete="username" required autoFocus
              autoCapitalize="none" spellCheck={false}
              value={email} onChange={(e) => setEmail(e.target.value)}
              style={loginStyles.input}
            />
          </label>
          <label style={loginStyles.label}>
            <span style={loginStyles.labelText}>PASSWORD</span>
            <input
              type="password" autoComplete="current-password" required
              value={password} onChange={(e) => setPassword(e.target.value)}
              style={loginStyles.input}
            />
          </label>
          {error && <div style={loginStyles.error}>{error}</div>}
          <button type="submit" disabled={submitting} style={{ ...loginStyles.button, opacity: submitting ? 0.6 : 1 }}>
            {submitting ? 'Signing in…' : 'Sign in'}
          </button>
          <div style={loginStyles.hint}>Accounts are created by the administrator.</div>
        </form>
      </div>
    );
  }

  // authed — expose user + logout on window for other components to consume.
  if (typeof window !== 'undefined') {
    window.__zenUser = state.user;
    window.__zenLogout = logout;
  }
  return children;
}

const loginStyles = {
  center: {
    position: 'fixed', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
    background: '#fafaf5',
    fontFamily: 'Geist, -apple-system, sans-serif',
    padding: 24,
  },
  spinner: {
    fontSize: 48, color: '#1a1a1a44', fontFamily: 'serif',
    animation: 'spin 1.2s linear infinite',
  },
  card: {
    width: 'min(400px, 100%)',
    background: '#fff',
    border: '1px solid #1a1a1a14',
    borderRadius: 8,
    boxShadow: '0 24px 56px -28px #1a1a1a30, 0 1px 0 #1a1a1a06',
    padding: '32px 28px',
    display: 'flex', flexDirection: 'column', gap: 14,
  },
  brand: {
    display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
    marginBottom: 12,
  },
  brandName: { fontFamily: 'Cormorant Garamond, serif', fontSize: 24, fontWeight: 500, marginTop: 6 },
  brandSub: { fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.18em', color: '#1a1a1a88' },
  label: { display: 'flex', flexDirection: 'column', gap: 4 },
  labelText: { fontFamily: 'JetBrains Mono, monospace', fontSize: 10, letterSpacing: '0.18em', color: '#1a1a1a88' },
  input: {
    fontFamily: 'Geist, sans-serif', fontSize: 14, padding: '10px 12px',
    border: '1px solid #1a1a1a30', borderRadius: 6, outline: 'none',
    background: '#fafaf5', minHeight: 44,
  },
  error: {
    fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: '#8a2820',
    background: '#fff3f0', border: '1px solid #c84a3230', borderRadius: 6,
    padding: '8px 10px',
  },
  button: {
    fontFamily: 'Geist, sans-serif', fontSize: 14, fontWeight: 500,
    padding: '12px 16px', background: '#1a1a1a', color: '#fafaf5',
    border: 'none', borderRadius: 999, cursor: 'pointer', marginTop: 4,
    minHeight: 44,
  },
  hint: {
    fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: '#1a1a1a66',
    textAlign: 'center', marginTop: 6,
  },
};

if (typeof window !== 'undefined') Object.assign(window, { LoginGate });
