// screen-signup.jsx — create-account form, wired to POST /auth/signup then an
// immediate login. Styled with the same primitives (Field, Btn) and brand
// header as screen-login.jsx so the two read as one flow. The fields mirror
// SaveHor's other frontend one-for-one: full name, email, unit name, password
// (+ confirm) and a terms checkbox. The backend links the account to an
// EXISTING household by unit name (it does not create one) — hence the helper
// under that field. On success it logs in and hands the session up via
// onLoggedIn, exactly like LoginScreen; onBack returns to the login screen.

function SignupScreen({ c, onLoggedIn, onBack }) {
  const { useState } = React;
  const tr = useT();
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [unit, setUnit] = useState('');
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [terms, setTerms] = useState(false);
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);
  const [stage, setStage] = useState('idle');   // 'idle' | 'creating' | 'loggingIn'

  const clearErr = (setter) => (e) => { setter(e.target.value); setError(''); };

  const canSubmit =
    name.trim() && email.trim() && unit.trim() && password && confirm && terms && !busy;

  const submit = async (e) => {
    if (e) e.preventDefault();
    // Field-level checks give a specific message rather than a dead button.
    if (!name.trim() || !email.trim() || !unit.trim() || !password || !confirm) {
      setError(tr('signup.err.fillAll')); return;
    }
    if (password.length < 6) { setError(tr('signup.err.pwLen')); return; }
    if (password !== confirm) { setError(tr('signup.err.pwMatch')); return; }
    if (!terms) { setError(tr('signup.err.terms')); return; }

    setBusy(true);
    setError('');
    try {
      setStage('creating');
      await SaveHorAPI.signup(email.trim(), password, name.trim(), unit.trim());
      // The signup endpoint returns no token, so log in to start a session —
      // same auto-login the app's other frontend does.
      setStage('loggingIn');
      const data = await SaveHorAPI.login(email.trim(), password);
      onLoggedIn?.(data);
    } catch (err) {
      setError(err.message || 'Sign-up failed.');
      setBusy(false);
      setStage('idle');
    }
  };

  const submitLabel = stage === 'loggingIn'
    ? tr('signup.loggingIn')
    : stage === 'creating'
      ? tr('signup.working')
      : tr('signup.submit');

  return (
    <div style={{
      flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0,
      overflowY: 'auto', background: c.bg,
    }}>
      {/* back to login */}
      <div style={{ padding: '14px 24px 0' }}>
        <button onClick={onBack} aria-label={tr('signup.login')} style={{
          width: 36, height: 36, border: 'none', background: 'transparent', cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0,
        }}>
          <IcArrowL size={20} color={c.text} />
        </button>
      </div>

      <div style={{ padding: '4px 28px 32px', display: 'flex', flexDirection: 'column' }}>
        {/* brand + heading */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14, marginBottom: 22 }}>
          <img src="logo/logo.png" alt="Save Hor!" style={{
            width: 88, height: 'auto', borderRadius: 18, display: 'block',
            boxShadow: '0 10px 30px rgba(31,42,36,0.18)',
          }} />
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 24, fontWeight: 700, color: c.text, letterSpacing: -0.5 }}>{tr('signup.title')}</div>
            <div style={{ fontSize: 14, color: c.textMuted, marginTop: 4 }}>{tr('signup.sub')}</div>
          </div>
        </div>

        {/* form */}
        <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Field
            label={tr('signup.name')} type="text" placeholder={tr('signup.namePlaceholder')}
            value={name} onChange={clearErr(setName)} c={c} />
          <Field
            label={tr('signup.email')} type="email" placeholder={tr('signup.emailPlaceholder')}
            value={email} onChange={clearErr(setEmail)} c={c} />
          <Field
            label={tr('signup.unit')} type="text" placeholder={tr('signup.unitPlaceholder')}
            helper={tr('signup.unitHelper')}
            value={unit} onChange={clearErr(setUnit)} c={c} />
          <Field
            label={tr('signup.password')} type="password" placeholder={tr('signup.passwordPlaceholder')}
            value={password} onChange={clearErr(setPassword)} c={c} />
          <Field
            label={tr('signup.confirm')} type="password" placeholder={tr('signup.passwordPlaceholder')}
            value={confirm} onChange={clearErr(setConfirm)} c={c} />

          {/* terms */}
          <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, cursor: 'pointer', marginTop: 2 }}>
            <input type="checkbox" checked={terms}
              onChange={(e) => { setTerms(e.target.checked); setError(''); }}
              style={{ width: 18, height: 18, marginTop: 1, accentColor: c.primary, flexShrink: 0, cursor: 'pointer' }} />
            <span style={{ fontSize: 13, color: c.textMuted, lineHeight: 1.4 }}>{tr('signup.terms')}</span>
          </label>

          {error && (
            <div style={{
              fontSize: 13, fontWeight: 500, color: c.danger,
              background: c.dangerSoft, borderRadius: 12, padding: '10px 14px', lineHeight: 1.4,
            }}>{error}</div>
          )}

          {/* Btn renders a typeless <button>, so inside the form it submits. */}
          <Btn kind="primary" size="lg" c={c} full disabled={!canSubmit}
            style={{ marginTop: 4 }}>
            {submitLabel}
          </Btn>
        </form>

        {/* footer link back to login */}
        <div style={{ textAlign: 'center', marginTop: 20, fontSize: 14, color: c.textMuted }}>
          {tr('signup.haveAccount')}{' '}
          <button onClick={onBack} style={{
            border: 'none', background: 'transparent', padding: 0, cursor: 'pointer',
            fontFamily: 'inherit', fontSize: 14, fontWeight: 600, color: c.primary,
          }}>{tr('signup.login')}</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { SignupScreen });
