/* ============================================================
   CADENCE — Auth screen (login / signup)
   window.AuthScreen — shown by app.jsx when window.CAD._authed is false.
   ============================================================ */
(function () {
  const { useState } = React;

  const ERROR_TEXT = {
    invalid_credentials: 'Incorrect username or password.',
    username_taken: 'That username is already taken.',
    invalid_username: 'Username must be at least 3 characters.',
    invalid_password: 'Password must be at least 6 characters.',
  };

  const inputStyle = {
    width: '100%',
    boxSizing: 'border-box',
    background: 'var(--surface-1)',
    border: '1px solid var(--border)',
    borderRadius: 10,
    color: 'var(--text)',
    fontFamily: 'var(--font-ui, inherit)',
    fontSize: 14,
    padding: '11px 13px',
    outline: 'none',
  };

  const labelStyle = {
    fontSize: 12,
    color: 'var(--text-mute)',
    fontWeight: 600,
    display: 'block',
    marginBottom: 6,
  };

  function Field({ label, children }) {
    return (
      <div style={{ marginBottom: 14 }}>
        <label style={labelStyle}>{label}</label>
        {children}
      </div>
    );
  }

  function AuthScreen() {
    const [mode, setMode] = useState('login');
    const [username, setUsername] = useState('');
    const [displayName, setDisplayName] = useState('');
    const [password, setPassword] = useState('');
    const [busy, setBusy] = useState(false);
    const [error, setError] = useState(null);

    const isSignup = mode === 'signup';

    const submit = async (event) => {
      event.preventDefault();
      if (busy) return;
      setBusy(true);
      setError(null);
      try {
        if (isSignup) {
          await window.CAD_API.signup(username.trim(), password, displayName.trim());
        } else {
          await window.CAD_API.login(username.trim(), password);
        }
        // Re-run the synchronous bootstrap path cleanly with the new cookie.
        window.location.reload();
      } catch (err) {
        setError(ERROR_TEXT[err?.message] || 'Something went wrong. Please try again.');
        setBusy(false);
      }
    };

    return (
      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
        <div className="panel" style={{ width: 380, maxWidth: '100%', padding: 28 }}>
          <div className="row gap8" style={{ alignItems: 'center', marginBottom: 4 }}>
            <div className="brand-mark" aria-hidden="true" style={{ width: 30, height: 30 }} />
            <div style={{ fontSize: 20, fontWeight: 700, letterSpacing: '-0.02em' }}>SoundExchange</div>
          </div>
          <div className="muted" style={{ fontSize: 13, marginBottom: 20 }}>
            {isSignup ? 'Create an account to start trading.' : 'Sign in to your account.'}
          </div>

          <form onSubmit={submit}>
            <Field label="Username">
              <input
                style={inputStyle}
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                autoComplete="username"
                placeholder="yourname"
              />
            </Field>

            {isSignup && (
              <Field label="Display name (optional)">
                <input
                  style={inputStyle}
                  value={displayName}
                  onChange={(e) => setDisplayName(e.target.value)}
                  autoComplete="nickname"
                  placeholder="Your Name"
                />
              </Field>
            )}

            <Field label="Password">
              <input
                style={inputStyle}
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                autoComplete={isSignup ? 'new-password' : 'current-password'}
                placeholder="••••••••"
              />
            </Field>

            {error && (
              <div style={{ color: 'var(--red, #f87171)', fontSize: 12.5, marginBottom: 12 }}>{error}</div>
            )}

            <button
              type="submit"
              className="btn btn-primary btn-block"
              disabled={busy}
              style={{ opacity: busy ? 0.7 : 1 }}
            >
              {busy ? 'Please wait…' : isSignup ? 'Create account' : 'Sign in'}
            </button>
          </form>

          <div className="muted" style={{ fontSize: 12.5, textAlign: 'center', marginTop: 16 }}>
            {isSignup ? 'Already have an account? ' : "Don't have an account? "}
            <a
              href="#"
              style={{ color: 'var(--blue-bright)', textDecoration: 'none' }}
              onClick={(e) => { e.preventDefault(); setError(null); setMode(isSignup ? 'login' : 'signup'); }}
            >
              {isSignup ? 'Sign in' : 'Sign up'}
            </a>
          </div>

          {!isSignup && (
            <div className="muted" style={{ fontSize: 11.5, textAlign: 'center', marginTop: 14, opacity: 0.8 }}>
              Demo account — username <b style={{ color: 'var(--text-dim)' }}>demo</b>, password <b style={{ color: 'var(--text-dim)' }}>cadence123</b>
            </div>
          )}
        </div>
      </div>
    );
  }

  window.AuthScreen = AuthScreen;
})();
