/**
 * Sign-in and sign-up screen.
 *
 * Shown only when a Firebase config is present (see lib/firebase-config.js).
 * Each employee has their own account, which is what lets their progress follow
 * them between the ward PC and their phone.
 */

(function () {
'use strict';

const { useState } = React;

function Field({ id, label, type = 'text', value, onChange, autoComplete, hint, dir, maxLength }) {
  return (
    <div className="field">
      <label className="field__label" htmlFor={id}>{label}</label>
      <input
        id={id}
        className="field__input"
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        autoComplete={autoComplete}
        dir={dir}
        maxLength={maxLength}
        required
      />
      {hint && <div className="field__hint">{hint}</div>}
    </div>
  );
}

const SEEN_KEY = 'radiology-academy/has-account';

/** Whether anyone has signed in on this browser before. Decides the first screen. */
function seenAccount() {
  try { return window.localStorage.getItem(SEEN_KEY) === '1'; } catch (err) { return true; }
}
function markSeen() {
  try { window.localStorage.setItem(SEEN_KEY, '1'); } catch (err) { /* ignore */ }
}

/** Sign-in failures that, for a first-time user, almost always mean "not registered yet". */
const NOT_REGISTERED_HINT = new Set(['auth/invalid-credential', 'auth/user-not-found', 'auth/wrong-password']);

function AuthScreen({ bootError }) {
  // A new employee on a fresh browser lands on sign-up: starting on sign-in
  // made the first attempt fail with "wrong password" for an account that
  // did not exist yet.
  const [mode, setMode] = useState(() => (seenAccount() ? 'signin' : 'signup')); // signin | signup | reset
  const [hint, setHint] = useState(false);
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [remember, setRemember] = useState(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState(bootError || '');
  const [notice, setNotice] = useState('');

  function switchMode(next) {
    setMode(next);
    setError('');
    setNotice('');
    setHint(false);
  }

  async function submit(e) {
    e.preventDefault();
    setError('');
    setNotice('');
    setHint(false);

    if (mode === 'signup' && name.trim().length < 2) {
      setError('יש להזין שם מלא — כך תופיע בדוח ההתקדמות.');
      return;
    }

    setBusy(true);
    try {
      if (mode === 'signin') {
        await window.Cloud.signIn(email, password, remember);
        markSeen();
      } else if (mode === 'signup') {
        await window.Cloud.signUp(name, email, password, remember);
        markSeen();
      } else {
        await window.Cloud.resetPassword(email);
        setNotice('אם קיים חשבון עם האימייל הזה, נשלח אליו קישור לאיפוס סיסמה.');
      }
      // On success the auth listener in the shell takes over.
    } catch (err) {
      setError(window.Cloud.message(err));
      if (mode === 'signin' && err && NOT_REGISTERED_HINT.has(err.code)) setHint(true);
      if (mode === 'signup' && err && err.code === 'auth/email-already-in-use') markSeen();
    } finally {
      setBusy(false);
    }
  }

  const title = mode === 'signin' ? 'כניסה למערך' : mode === 'signup' ? 'הרשמה למערך' : 'איפוס סיסמה';
  const action = mode === 'signin' ? 'כניסה' : mode === 'signup' ? 'יצירת חשבון' : 'שליחת קישור איפוס';

  return (
    <div className="auth">
      <div className="auth__panel card animate-in">
        <div className="brand" style={{ marginBottom: 'var(--space-4)' }}>
          <span className="brand__mark" aria-hidden="true">◉</span>
          <span>מערך הדימות</span>
        </div>

        <h1 className="auth__title">{title}</h1>
        <p className="auth__lead">
          {mode === 'signup'
            ? 'החשבון שומר את ההתקדמות שלך — שיעורים, מבחנים ותרגילים — ומאפשר להמשיך מכל מכשיר.'
            : mode === 'reset'
              ? 'נשלח אליך קישור לבחירת סיסמה חדשה.'
              : 'ההתקדמות שלך נשמרת בחשבון וממשיכה איתך בין מכשירים.'}
        </p>

        <form onSubmit={submit} className="auth__form" noValidate>
          {mode === 'signup' && (
            <Field id="auth-name" label="שם מלא" value={name} onChange={setName} autoComplete="name" maxLength={window.Cloud.NAME_MAX || 120} />
          )}
          <Field id="auth-email" label="אימייל" type="email" value={email} onChange={setEmail} autoComplete="email" dir="ltr" />
          {mode !== 'reset' && (
            <Field
              id="auth-password"
              label="סיסמה"
              type="password"
              value={password}
              onChange={setPassword}
              autoComplete={mode === 'signup' ? 'new-password' : 'current-password'}
              hint={mode === 'signup' ? 'לפחות 6 תווים.' : null}
              dir="ltr"
            />
          )}

          {mode !== 'reset' && (
            <label className="field__check">
              <input type="checkbox" checked={remember} onChange={(e) => setRemember(e.target.checked)} />
              <span>
                להישאר מחובר במכשיר הזה
                <span className="field__hint">רק במכשיר אישי. במחשב משותף במחלקה להשאיר לא מסומן — החיבור יסתיים כשהדפדפן ייסגר.</span>
              </span>
            </label>
          )}

          {error && (
            <div className="callout callout--warn" role="alert" style={{ margin: 0 }}>
              {error}
              {hint && (
                <div style={{ marginTop: 'var(--space-2)' }}>
                  אם זו הפעם הראשונה שלך במערך, צריך קודם ליצור חשבון.{' '}
                  <button type="button" className="btn btn--ghost btn--sm" onClick={() => switchMode('signup')}>
                    להרשמה
                  </button>
                </div>
              )}
            </div>
          )}
          {notice && <div className="callout callout--note" role="status" style={{ margin: 0 }}>{notice}</div>}

          <button type="submit" className="btn btn--primary btn--block" disabled={busy}>
            {busy ? 'רגע…' : action}
          </button>
        </form>

        <div className="auth__switch">
          {mode === 'signin' && (
            <>
              <button type="button" className="btn btn--ghost btn--sm" onClick={() => switchMode('signup')}>
                אין לך חשבון? הרשמה
              </button>
              <button type="button" className="btn btn--ghost btn--sm" onClick={() => switchMode('reset')}>
                שכחתי סיסמה
              </button>
            </>
          )}
          {mode !== 'signin' && (
            <button type="button" className="btn btn--ghost btn--sm" onClick={() => switchMode('signin')}>
              {mode === 'signup' ? 'כבר יש לך חשבון? כניסה' : 'חזרה לכניסה'}
            </button>
          )}
        </div>

        <p className="auth__fine">
          נשמרים: שם, אימייל והתקדמות בלימוד בלבד. המערך אינו כלי אבחון ואינו תחליף להכשרה קלינית מוסמכת.
        </p>
      </div>
    </div>
  );
}

function BootScreen({ text }) {
  return (
    <div className="auth">
      <div className="auth__panel card" role="status" style={{ textAlign: 'center' }}>
        <span className="brand__mark breathe" aria-hidden="true">◉</span>
        <p style={{ marginTop: 'var(--space-3)', color: 'var(--text-muted)' }}>{text}</p>
      </div>
    </div>
  );
}

window.AuthScreen = AuthScreen;
window.BootScreen = BootScreen;

})();
