/* Auth — its own shell, no navigation owner (AGENTS §7.1): no top bar, no
   destinations, no account menu. One layout variant: centred card, the carrier
   mark above the form as the only navigation. One credential strategy:
   password. No providers, because this project ships no `assets/providers/`
   marks and §7.4 forbids drawing them. Designed states: idle, field-invalid,
   submitting, signed-out. Rate limiting, lockout, MFA and password reset are
   out of scope for this template, so nothing links to them.

   Commit model: STAGED, as §7.3 requires of every auth form. */
(() => {
  const {
    Card, CardHeader, CardTitle, CardDescription, CardPanel,
    Field, FieldLabel, FieldError, Input, Button,
  } = window.OriginDesignSystem_7c998b;

  const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;

  function AuthShell({ carrier, children, footer }) {
    return (
      <div className="cd-auth">
        <div className="cd-auth__col">
          <div className="cd-auth__mark">
            <img className="cd-auth__logo" src="../../assets/templates/logos/03-logo-demo.svg" alt="" width="40" height="40" />
            <span className="cd-auth__words">
              <span className="cd-brand__name">{carrier.name}</span>
              <span className="cd-auth__desk">{carrier.desk}</span>
            </span>
          </div>
          {children}
          {footer ? <p className="cd-auth__foot">{footer}</p> : null}
        </div>
      </div>
    );
  }

  function SignInScreen({ carrier, user, onSignIn }) {
    const [values, setValues] = React.useState({ email: "", password: "" });
    const [submitted, setSubmitted] = React.useState(false);
    const [pending, setPending] = React.useState(false);
    const errors = {};
    if (!EMAIL.test(values.email)) errors.email = "Enter a valid email address.";
    if (values.password.length < 8) errors.password = "Your password is at least 8 characters.";
    const valid = Object.keys(errors).length === 0;
    const dirty = values.email !== "" || values.password !== "";
    const submit = () => {
      setSubmitted(true);
      if (!valid) return;
      setPending(true);
      window.setTimeout(() => { setPending(false); onSignIn(); }, 600);
    };
    return (
      <AuthShell carrier={carrier} footer={carrier.region + " cargo claims."}>
        <Card>
          <CardHeader>
            <CardTitle>Sign in</CardTitle>
            <CardDescription>To the {carrier.name} {carrier.desk.toLowerCase()}.</CardDescription>
          </CardHeader>
          <CardPanel>
            <form className="cd-fields" onSubmit={(e) => { e.preventDefault(); submit(); }}>
              <Field>
                <FieldLabel htmlFor="cd-signin-email">Email</FieldLabel>
                <Input id="cd-signin-email" type="email" autoComplete="email" placeholder={user.email} value={values.email}
                  invalid={submitted && !!errors.email} onChange={(e) => setValues(Object.assign({}, values, { email: e.target.value }))} />
                {submitted && errors.email ? <FieldError>{errors.email}</FieldError> : null}
              </Field>
              <Field>
                <FieldLabel htmlFor="cd-signin-password">Password</FieldLabel>
                <Input id="cd-signin-password" type="password" autoComplete="current-password" value={values.password}
                  invalid={submitted && !!errors.password} onChange={(e) => setValues(Object.assign({}, values, { password: e.target.value }))} />
                {submitted && errors.password ? <FieldError>{errors.password}</FieldError> : null}
              </Field>
              <Button type="submit" loading={pending} disabled={!dirty || pending}>Sign in</Button>
            </form>
          </CardPanel>
        </Card>
      </AuthShell>
    );
  }

  function SignedOutScreen({ carrier, user, onSignIn }) {
    return (
      <AuthShell carrier={carrier} footer="Time bars keep running whether anybody is signed in or not.">
        <Card>
          <CardHeader>
            <CardTitle>You are signed out</CardTitle>
            <CardDescription>{user.name} was signed out of the {carrier.name} {carrier.desk.toLowerCase()}.</CardDescription>
          </CardHeader>
          <CardPanel>
            <Button onClick={onSignIn}>Sign in</Button>
          </CardPanel>
        </Card>
      </AuthShell>
    );
  }

  Object.assign(window, { SignInScreen, SignedOutScreen, AuthShell });
})();
