/* Password recovery and lockout — the four reset screens AGENTS §7.5 requires,
   plus the lockout state §7.3.6 requires, all on the same auth shell as sign-in:
   its own shell, no navigation owner, one layout variant (centred card).

   One state per screen, and the four are four screens rather than four states of
   one, because each has a different single action:
     /forgot-password         request a link      → Send reset link
     /forgot-password/sent    the confirmation    → Resend, with a cooldown
     /reset-password          set the new one     → Set new password
     /reset-password/done     the consequence     → Sign in
     /reset-password/expired  the dead link       → Send a new link
     /account-locked          the wait            → a real countdown

   Enumeration-safe throughout: nothing on the request or the confirmation
   screen says whether an account exists (§7.3.2). Every screen has a way back
   to sign-in, so nothing here is a dead end. Requirements render from
   PASSWORD_RULES, which is also what blocks the submit. */
(() => {
  const {
    Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter,
    Field, FieldLabel, FieldDescription, FieldError, Input, Button, Alert, AlertTitle, AlertDescription,
  } = window.OriginDesignSystem_7c998b;

  const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
  /* The link's life and the resend cooldown, stated once and rendered from here
     rather than written into the copy twice. */
  const LINK_MINUTES = 30;
  const RESEND_SECONDS = 45;

  function BackToSignIn({ onNavigate, label }) {
    return <Button variant="ghost" size="sm" onClick={() => onNavigate("/signin")}>{label || "Back to sign in"}</Button>;
  }

  function ForgotPasswordScreen({ agency, onNavigate, onRequest }) {
    const [email, setEmail] = React.useState("");
    const [submitted, setSubmitted] = React.useState(false);
    const [pending, setPending] = React.useState(false);
    const error = EMAIL.test(email) ? null : "Enter a valid email address.";
    const submit = () => {
      setSubmitted(true);
      if (error) return;
      setPending(true);
      window.setTimeout(() => { setPending(false); onRequest(email.trim()); }, 600);
    };
    return (
      <AuthShell agency={agency} footer="Nobody at the agency can read your password, so this is the only way back in.">
        <Card>
          <CardHeader>
            <CardTitle>Reset your password</CardTitle>
            <CardDescription>We will email a link that sets a new one. It is good for {LINK_MINUTES} minutes.</CardDescription>
          </CardHeader>
          <CardPanel>
            <form className="mq-fields" onSubmit={(e) => { e.preventDefault(); submit(); }}>
              <Field>
                <FieldLabel htmlFor="mq-fp-email">Email</FieldLabel>
                <Input id="mq-fp-email" type="email" autoComplete="email" value={email}
                  invalid={submitted && !!error} onChange={(e) => setEmail(e.target.value)} />
                {submitted && error ? <FieldError>{error}</FieldError> : <FieldDescription>The address you sign in with.</FieldDescription>}
              </Field>
              <Button type="submit" loading={pending} disabled={!email || pending}>Send reset link</Button>
            </form>
          </CardPanel>
          <CardFooter className="mq-card-footer">
            <BackToSignIn onNavigate={onNavigate} />
          </CardFooter>
        </Card>
      </AuthShell>
    );
  }

  function ResetSentScreen({ agency, email, onNavigate, onResend }) {
    /* A cooldown with a real countdown, not a disabled button that never says
       why (§7.5). */
    const [left, setLeft] = React.useState(RESEND_SECONDS);
    React.useEffect(() => {
      if (left <= 0) return undefined;
      const t = window.setTimeout(() => setLeft((n) => n - 1), 1000);
      return () => window.clearTimeout(t);
    }, [left]);
    return (
      <AuthShell agency={agency} footer="If it does not arrive, check the spam folder before asking for another.">
        <Card>
          <CardHeader>
            <CardTitle>Check your email</CardTitle>
            <CardDescription>
              If an account exists for {email ? <strong>{email}</strong> : "that address"}, a link to set a new password is on its way. It expires {LINK_MINUTES} minutes after it was sent.
            </CardDescription>
          </CardHeader>
          <CardPanel>
            <div className="mq-fields">
              <Button variant="outline" disabled={left > 0} onClick={() => { setLeft(RESEND_SECONDS); onResend(); }}>
                {left > 0 ? "Resend link in " + left + "s" : "Resend link"}
              </Button>
              <p className="mq-note">Opening the link signs you out everywhere else, on this desk and on your phone.</p>
            </div>
          </CardPanel>
          <CardFooter className="mq-card-footer">
            <BackToSignIn onNavigate={onNavigate} />
            <Button variant="ghost" size="sm" onClick={() => onNavigate("/reset-password")}>I have the link</Button>
          </CardFooter>
        </Card>
      </AuthShell>
    );
  }

  function SetPasswordScreen({ agency, email, onNavigate, onSet }) {
    const [value, setValue] = React.useState("");
    const [reveal, setReveal] = React.useState(false);
    const [submitted, setSubmitted] = React.useState(false);
    const [pending, setPending] = React.useState(false);
    const met = PASSWORD_RULES.map((rule) => ({ rule: rule, ok: rule.test(value) }));
    const valid = passwordMeets(value);
    const submit = () => {
      setSubmitted(true);
      if (!valid) return;
      setPending(true);
      window.setTimeout(() => { setPending(false); onSet(); }, 600);
    };
    return (
      <AuthShell agency={agency} footer="One password, one field. A reveal toggle beats a confirm box you cannot read either.">
        <Card>
          <CardHeader>
            <CardTitle>Set a new password</CardTitle>
            <CardDescription>For {email || "your account"} on the {agency.desk.toLowerCase()}.</CardDescription>
          </CardHeader>
          <CardPanel>
            <form className="mq-fields" onSubmit={(e) => { e.preventDefault(); submit(); }}>
              <Field>
                <FieldLabel htmlFor="mq-rp-password">New password</FieldLabel>
                <Input id="mq-rp-password" type={reveal ? "text" : "password"} autoComplete="new-password" value={value}
                  invalid={submitted && !valid} onChange={(e) => setValue(e.target.value)}
                  endAddon={<button type="button" className="mq-link" aria-label={reveal ? "Hide password" : "Show password"} onClick={() => setReveal(!reveal)}>{reveal ? "Hide" : "Show"}</button>} />
                {submitted && !valid ? <FieldError>Your password has to meet all three requirements below.</FieldError> : null}
              </Field>
              <div className="mq-checks">
                {met.map((row) => (
                  <span className={"mq-check " + (row.ok ? "mq-good" : "mq-muted")} key={row.rule.id}>
                    <Icon name={row.ok ? "check" : "circle"} size={14} />
                    <span className="mq-check__text">{row.rule.label}</span>
                  </span>
                ))}
              </div>
              <Button type="submit" loading={pending} disabled={!value || pending}>Set new password</Button>
            </form>
          </CardPanel>
          <CardFooter className="mq-card-footer">
            <BackToSignIn onNavigate={onNavigate} />
            <Button variant="ghost" size="sm" onClick={() => onNavigate("/reset-password/expired")}>My link has expired</Button>
          </CardFooter>
        </Card>
      </AuthShell>
    );
  }

  function ResetDoneScreen({ agency, onNavigate }) {
    return (
      <AuthShell agency={agency} footer="Nothing on the desk changed: pitches already sent stay sent.">
        <Card>
          <CardHeader>
            <CardTitle>Password set</CardTitle>
            <CardDescription>Every other session was signed out, including your phone. Sign in again with the new password.</CardDescription>
          </CardHeader>
          <CardPanel>
            <Button onClick={() => onNavigate("/signin")}>Sign in</Button>
          </CardPanel>
        </Card>
      </AuthShell>
    );
  }

  function ResetExpiredScreen({ agency, onNavigate }) {
    return (
      <AuthShell agency={agency} footer="Links are short-lived on purpose; asking for another costs nothing.">
        <Card>
          <CardHeader>
            <CardTitle>That link has expired</CardTitle>
            <CardDescription>Reset links last {LINK_MINUTES} minutes and can only be used once. Nothing has changed about your account.</CardDescription>
          </CardHeader>
          <CardPanel>
            <Button onClick={() => onNavigate("/forgot-password")}>Send a new link</Button>
          </CardPanel>
          <CardFooter className="mq-card-footer">
            <BackToSignIn onNavigate={onNavigate} />
          </CardFooter>
        </Card>
      </AuthShell>
    );
  }

  function AccountLockedScreen({ agency, minutes, onNavigate }) {
    /* A bounded wait with a real countdown, and a recovery path on the same
       screen — never a toast (§7.3.6). */
    const [left, setLeft] = React.useState((minutes || 15) * 60);
    React.useEffect(() => {
      if (left <= 0) return undefined;
      const t = window.setTimeout(() => setLeft((n) => n - 1), 1000);
      return () => window.clearTimeout(t);
    }, [left]);
    const mm = Math.floor(left / 60), ss = left % 60;
    return (
      <AuthShell agency={agency} footer="The lock is on the account, not on the device — waiting it out on another browser will not help.">
        <Card>
          <CardHeader>
            <CardTitle>This account is locked</CardTitle>
            <CardDescription>{AGENCY_POLICY.signInAttempts} passwords were tried and none matched, so sign-in is closed for fifteen minutes.</CardDescription>
          </CardHeader>
          <CardPanel>
            <div className="mq-fields">
              {left > 0 ? (
                <Alert variant="warning">
                  <AlertTitle>Try again in {mm}:{String(ss).padStart(2, "0")}</AlertTitle>
                  <AlertDescription>Resetting your password opens it immediately — you do not have to wait for the clock.</AlertDescription>
                </Alert>
              ) : (
                <Alert variant="success">
                  <AlertTitle>The wait is over</AlertTitle>
                  <AlertDescription>You can sign in again now.</AlertDescription>
                </Alert>
              )}
              <Button onClick={() => onNavigate(left > 0 ? "/forgot-password" : "/signin")}>{left > 0 ? "Reset my password" : "Sign in"}</Button>
            </div>
          </CardPanel>
          <CardFooter className="mq-card-footer">
            <span className="mq-note">Still stuck? {agency.billingEmail.replace("billing", "help")} reaches a person.</span>
          </CardFooter>
        </Card>
      </AuthShell>
    );
  }

  Object.assign(window, { ForgotPasswordScreen, ResetSentScreen, SetPasswordScreen, ResetDoneScreen, ResetExpiredScreen, AccountLockedScreen });
})();
