/* Auth — its own shell, and the only shell in the product with NO navigation
   owner (AGENTS §7.1): no sidebar, no account menu, no destinations.
   Layout variant, one for the product: SPLIT, with the form side the wider of
   the two. The brand side is a neutral plane carrying one piece of art — a dot
   grid faded out from the bottom-left, geometry rather than illustration.
   Every screen here is STAGED. One state per screen, and a server error and a
   field error never render for the same submission.
   Strategy: password, one credential. No providers are offered because this
   project ships no official provider marks (§7.4) — an entry point without a
   screen behind it is worse than none. */
(() => {
  const {
    Button, Input, Alert, AlertTitle, AlertDescription, Field, FieldLabel, FieldDescription, FieldError, Separator,
  } = window.OriginDesignSystem_7c998b;

  function AuthShell({ title, lede, children, foot }) {
    return (
      <div className="hh-auth">
        <aside className="hh-auth__side">
          <span className="hh-auth__art" aria-hidden="true" />
          <span className="hh-auth__mark">
            <img src={HEARTH_MARK} alt="" width="22" height="22" />
            Hearth
          </span>
          <p className="hh-auth__claim">One place for the house: what it is doing, what it costs, and who is in it.</p>
          <p className="hh-auth__fine">{RESIDENCE.address}. Hearth can unlock doors and disarm the alarm, so everything you open is recorded against your name.</p>
        </aside>
        <main className="hh-auth__formside">
          <div className="hh-auth__form">
            <div>
              <h1 className="hh-auth__title">{title}</h1>
              <p className="hh-auth__lede">{lede}</p>
            </div>
            {children}
            {foot ? <p className="hh-auth__foot">{foot}</p> : null}
          </div>
        </main>
      </div>
    );
  }

  function SignInScreen({ onSignIn, onNavigate }) {
    const [email, setEmail] = React.useState("");
    const [password, setPassword] = React.useState("");
    const [reveal, setReveal] = React.useState(false);
    const [submitted, setSubmitted] = React.useState(false);
    const [rejected, setRejected] = React.useState(false);
    const dirty = !!email || !!password;

    const errors = {};
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email.trim())) errors.email = "Enter a valid email address.";
    if (password.length < 8) errors.password = "Your password is at least 8 characters.";
    const valid = Object.keys(errors).length === 0;

    const submit = () => {
      setSubmitted(true);
      if (!valid) { setRejected(false); return; }
      /* One state per submission: a server error only where there is no field
         error, and the password field is the only thing cleared. */
      if (email.trim().toLowerCase().indexOf("@blackthorn.house") < 0) { setRejected(true); setPassword(""); return; }
      setRejected(false);
      onSignIn();
    };

    return (
      <AuthShell title="Sign in" lede="Use your household account. Every adult in the house has their own."
        foot={<>Not in the household yet? Whoever set the house up can invite you — ask them, rather than making a second account.</>}>
        {rejected ? (
          <Alert variant="error">
            <AlertTitle>Email or password is incorrect</AlertTitle>
            <AlertDescription>Check the address and try again. After five attempts the account locks for fifteen minutes.</AlertDescription>
          </Alert>
        ) : null}
        <div className="hh-auth__fields">
          <Field>
            <FieldLabel htmlFor="hh-si-email">Email</FieldLabel>
            <Input id="hh-si-email" type="email" autoComplete="email" value={email} placeholder="sofia@blackthorn.house"
              invalid={submitted && !!errors.email} onChange={(e) => setEmail(e.target.value)} />
            {submitted && errors.email ? <FieldError>{errors.email}</FieldError> : null}
          </Field>
          <Field>
            <span className="hh-auth__row">
              <FieldLabel htmlFor="hh-si-password">Password</FieldLabel>
              <Button variant="link" size="xs" onClick={() => onNavigate("/forgot-password")}>Forgot password?</Button>
            </span>
            <Input id="hh-si-password" type={reveal ? "text" : "password"} autoComplete="current-password" value={password}
              invalid={submitted && !!errors.password} onChange={(e) => setPassword(e.target.value)}
              endAddon={
                <Button variant="ghost" size="icon-xs" aria-label={reveal ? "Hide password" : "Show password"} onClick={() => setReveal(!reveal)}>
                  <Icon name={reveal ? "eye-off" : "eye"} size={14} />
                </Button>
              } />
            {submitted && errors.password ? <FieldError>{errors.password}</FieldError> : null}
          </Field>
          <Button disabled={!dirty} onClick={submit}>Sign in</Button>
        </div>
      </AuthShell>
    );
  }

  function ForgotPasswordScreen({ email, onSubmit, onNavigate }) {
    const [value, setValue] = React.useState(email || "");
    const [submitted, setSubmitted] = React.useState(false);
    const error = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value.trim()) ? null : "Enter a valid email address.";
    return (
      <AuthShell title="Forgot password" lede="We will send a link that sets a new password. It works once and expires after an hour."
        foot={<>Remembered it? <Button variant="link" size="xs" onClick={() => onNavigate("/signin")}>Back to sign in</Button></>}>
        <div className="hh-auth__fields">
          <Field>
            <FieldLabel htmlFor="hh-fp-email">Email</FieldLabel>
            <Input id="hh-fp-email" type="email" autoComplete="username" value={value} placeholder="sofia@blackthorn.house"
              invalid={submitted && !!error} onChange={(e) => setValue(e.target.value)} />
            {submitted && error ? <FieldError>{error}</FieldError> : <FieldDescription>The address the household invitation went to.</FieldDescription>}
          </Field>
          <Button disabled={!value} onClick={() => { setSubmitted(true); if (!error) onSubmit(value.trim()); }}>Send reset link</Button>
        </div>
      </AuthShell>
    );
  }

  function ResetLinkSentScreen({ email, onNavigate }) {
    return (
      <AuthShell title="Check your email"
        lede={"If an account exists for " + email + ", we have sent a link that sets a new password. It expires in " + HEARTH_RESET_LINK.expiresInMinutes + " minutes."}
        foot={<>Nothing within ten minutes? Check the junk folder. Another adult in the household can also reset it for you.</>}>
        <div className="hh-auth__fields">
          <Button variant="outline" onClick={() => onNavigate("/forgot-password")}>Send it again</Button>
          <Separator />
          <Button variant="link" onClick={() => onNavigate("/signin")}>Back to sign in</Button>
        </div>
      </AuthShell>
    );
  }

  function SetNewPasswordScreen({ now, onSubmit, onNavigate }) {
    const [value, setValue] = React.useState("");
    const [reveal, setReveal] = React.useState(false);
    const [submitted, setSubmitted] = React.useState(false);
    const met = PASSWORD_RULES.map((rule) => ({ id: rule.id, label: rule.label, ok: rule.test(value) }));
    const valid = met.every((r) => r.ok);
    const minutesLeft = Math.max(0, HEARTH_RESET_LINK.expiresInMinutes - Math.round((now - HEARTH_RESET_LINK.issuedAt) / 6e4));
    return (
      <AuthShell title="Set a new password"
        lede={"For " + HEARTH_RESET_LINK.email + ". This link expires in " + minutesLeft + " minutes and works once."}
        foot={<>Expired while you were reading? <Button variant="link" size="xs" onClick={() => onNavigate("/reset-password/expired")}>See what to do</Button></>}>
        <div className="hh-auth__fields">
          <Field>
            <FieldLabel htmlFor="hh-rp-password">New password</FieldLabel>
            <Input id="hh-rp-password" type={reveal ? "text" : "password"} autoComplete="new-password" value={value}
              invalid={submitted && !valid} onChange={(e) => setValue(e.target.value)}
              endAddon={
                <Button variant="ghost" size="icon-xs" aria-label={reveal ? "Hide password" : "Show password"} onClick={() => setReveal(!reveal)}>
                  <Icon name={reveal ? "eye-off" : "eye"} size={14} />
                </Button>
              } />
            {submitted && !valid ? <FieldError>Your password does not meet every requirement yet.</FieldError> : null}
          </Field>
          <div className="hh-checklist">
            {met.map((rule) => (
              <span className="hh-checklist__item" key={rule.id} data-met={rule.ok ? "true" : "false"}>
                <Icon name={rule.ok ? "check" : "dot"} size={14} />{rule.label}
              </span>
            ))}
          </div>
          <Button disabled={!value} onClick={() => { setSubmitted(true); if (valid) onSubmit(); }}>Set new password</Button>
        </div>
      </AuthShell>
    );
  }

  function ResetLinkExpiredScreen({ onNavigate }) {
    return (
      <AuthShell title="That link has expired"
        lede={"A reset link works once and lasts " + HEARTH_RESET_LINK.expiresInMinutes + " minutes. Ask for a new one and it will arrive within a minute."}
        foot={<>If you did not ask for a reset, tell the other adults in the household — somebody may be trying the account.</>}>
        <div className="hh-auth__fields">
          <Button onClick={() => onNavigate("/forgot-password")}>Send a new link</Button>
          <Button variant="link" onClick={() => onNavigate("/signin")}>Back to sign in</Button>
        </div>
      </AuthShell>
    );
  }

  function PasswordResetDoneScreen({ email, onNavigate }) {
    return (
      <AuthShell title="Password changed"
        lede={"The password for " + email + " has been changed, and every other session has been signed out — including the tablet in the kitchen."}
        foot={<>Did not change it yourself? Sign in, then suspend your own access on People and ask another adult to help.</>}>
        <div className="hh-auth__fields">
          <Button onClick={() => onNavigate("/signin")}>Sign in</Button>
        </div>
      </AuthShell>
    );
  }

  Object.assign(window, { AuthShell, SignInScreen, ForgotPasswordScreen, ResetLinkSentScreen, SetNewPasswordScreen, ResetLinkExpiredScreen, PasswordResetDoneScreen });
})();
