/* ========================================================================
   roles-auth.jsx — Standalone screens outside the signed-in app shell.

   §5.1 Invitation acceptance and first sign-in
        happy path · expired (>48h) · already accepted · cancelled
   §5.2 Verified email change — confirmation landing
        success · expired (>24h) · already used · address now taken
   ======================================================================== */
const { useState: uAu } = React;

/* ---------- Shared shell for every out-of-app screen ---------- */
function AuthShell({ children, wide }) {
  return (
    <div className="mp-auth">
      <div className={"mp-auth-card" + (wide ? " mp-auth-card--wide" : "")}>
        <img src="assets/logos/mp-logo-moss.svg" alt="Meaningful Planet" className="mp-auth-logo" />
        {children}
      </div>
    </div>
  );
}

function AuthOutcome({ tone = "neutral", icon, title, body, note, actions }) {
  return (
    <AuthShell>
      <div className={"mp-auth-ic mp-auth-ic--" + tone}><Icon name={icon} size={26} /></div>
      <h1 className="mp-auth-title">{title}</h1>
      <p className="mp-auth-body">{body}</p>
      {note ? <div className="mp-auth-note"><Icon name="info" size={15} /><span>{note}</span></div> : null}
      <div className="mp-auth-actions">{actions}</div>
    </AuthShell>
  );
}

/* =====================================================================
   §5.1 — Invitation acceptance
   ===================================================================== */
const INVITE_DEMO = {
  name: "Sam Fielding",
  email: "sam.fielding@acmeco.co.uk",
  role: "admin",
  invitedBy: "Lewis Mangrove",
  company: "Acme Industries"
};

function AcceptInvitationScreen({ state }) {
  if (state === "expired") return (
    <AuthOutcome
      tone="warn" icon="clock-alert"
      title="This invitation has expired"
      body={"Invitations are valid for " + window.INVITE_TTL_H + " hours. Ask " + INVITE_DEMO.invitedBy + " or another administrator at " + INVITE_DEMO.company + " to send you a new one."}
      note="For security, you can't request a new invitation yourself."
      actions={<Button variant="secondary" href="#/signin">Go to Sign In</Button>}
    />
  );
  if (state === "accepted") return (
    <AuthOutcome
      tone="neutral" icon="circle-check"
      title="You've already accepted this invitation"
      body="Your account is set up. Sign in with your email address and the password you chose."
      actions={<Button variant="primary" href="#/signin">Sign In</Button>}
    />
  );
  if (state === "cancelled") return (
    <AuthOutcome
      tone="neutral" icon="link-2-off"
      title="This link is no longer valid"
      body="If you were expecting access, contact whoever invited you."
      actions={<Button variant="secondary" href="#/signin">Go to Sign In</Button>}
    />
  );
  return <AcceptInvitationForm />;
}

function AcceptInvitationForm() {
  const r = window.ROLES[INVITE_DEMO.role];
  const [name, setName] = uAu(INVITE_DEMO.name);
  const [pw, setPw] = uAu("");
  const [again, setAgain] = uAu("");
  const [err, setErr] = uAu(null);
  const [done, setDone] = uAu(false);

  const met = window.PW_REQS.map((q) => q.test(pw));
  const score = pw ? met.filter(Boolean).length : 0;

  const submit = () => {
    if (!name.trim()) return setErr("Enter your name so your colleagues know who you are.");
    if (score < 4) return setErr("Your password doesn't meet all of the requirements yet.");
    if (again !== pw) return setErr("The two passwords don't match.");
    setErr(null);
    setDone(true);
    setTimeout(() => { window.location.hash = "/dashboard"; }, 2200);
  };

  if (done) return (
    <AuthOutcome
      tone="ok" icon="circle-check"
      title={"Welcome to " + INVITE_DEMO.company}
      body={"Your account is ready and you're signed in as " + r.label + ". Taking you to your dashboard..."}
      note="We've sent a confirmation to your email address."
      actions={<Button variant="primary" href="#/dashboard">Go to Dashboard</Button>}
    />
  );

  return (
    <AuthShell wide>
      <h1 className="mp-auth-title">Set up your account</h1>
      <p className="mp-auth-body">
        <strong>{INVITE_DEMO.invitedBy}</strong> invited you to {INVITE_DEMO.company}. Choose a password and you're in.
      </p>

      <div className={"mp-only-role mp-only-role--" + INVITE_DEMO.role} style={{ margin: "18px 0 4px" }}>
        <span className={"mp-role-opt-ic mp-role-opt-ic--" + INVITE_DEMO.role}><Icon name={r.icon} size={16} /></span>
        <div>
          <div className="mp-role-opt-name">You'll join as {r.label}</div>
          <div className="mp-role-opt-desc">{r.long}</div>
        </div>
      </div>

      <div className="mp-auth-form">
        <div className="mp-field">
          <label className="mp-field-label">Email</label>
          <input className="mp-field-input" value={INVITE_DEMO.email} readOnly />
        </div>
        <div className="mp-field">
          <label className="mp-field-label">Full Name</label>
          <input className="mp-field-input" value={name} onChange={(e) => { setName(e.target.value); setErr(null); }} />
        </div>
        <div className="mp-field">
          <label className="mp-field-label">Create a password</label>
          <input className="mp-field-input" type="password" value={pw} placeholder="Create a secure password"
            onChange={(e) => { setPw(e.target.value); setErr(null); }} />
        </div>
        <div className="mp-pw-strength">
          <div className="mp-pw-bars">
            {[1, 2, 3, 4].map((i) => <span key={i} className={"mp-pw-bar" + (score >= i ? " is-on-" + score : "")} />)}
          </div>
          <div className="mp-pw-label">{score ? <>Password strength: <strong>{window.PW_WORDS[score]}</strong></> : "Password strength"}</div>
          <div className="mp-pw-reqs">
            {window.PW_REQS.map((q, i) => (
              <div key={q.label} className={"mp-pw-req" + (met[i] ? " is-met" : "")}>
                <span className="mp-pw-req-dot"><Icon name="check" size={10} /></span>
                <span>{q.label}</span>
              </div>
            ))}
          </div>
        </div>
        <div className="mp-field">
          <label className="mp-field-label">Re-enter password</label>
          <input className={"mp-field-input" + (err ? " has-err" : "")} type="password" value={again}
            placeholder="Type the password again" onChange={(e) => { setAgain(e.target.value); setErr(null); }} />
          {err ? <div className="mp-inline-err"><Icon name="triangle-alert" size={13} /><span>{err}</span></div> : null}
        </div>
        <Button variant="primary" size="lg" onClick={submit}>Create Account and Sign In</Button>
      </div>
    </AuthShell>
  );
}

/* =====================================================================
   §5.2 — Email change confirmation landing
   ===================================================================== */
function ConfirmEmailScreen({ state }) {
  const ctx = window.useRoles ? useRoles() : null;
  const me = ctx ? ctx.actor : null;
  const target = (me && me.pending_email) || "sam.fielding@acmeco.co.uk";

  if (state === "expired") return (
    <AuthOutcome
      tone="warn" icon="clock-alert"
      title="This link has expired"
      body={"Email confirmation links are valid for " + window.EMAIL_TTL_H + " hours. Your sign-in email hasn't changed — request the change again from Settings."}
      actions={<Button variant="primary" href="#/settings">Back to Profile</Button>}
    />
  );
  if (state === "used") return (
    <AuthOutcome
      tone="neutral" icon="link-2-off"
      title="This link is no longer valid"
      body="It's already been used, or a newer request replaced it. Your sign-in email is unchanged."
      actions={<Button variant="secondary" href="#/settings">Back to Profile</Button>}
    />
  );
  if (state === "taken") return (
    <AuthOutcome
      tone="err" icon="triangle-alert"
      title="That address is already in use"
      body={"Someone else claimed " + target + " before you confirmed. Your sign-in email is unchanged — try again with a different address."}
      actions={<Button variant="primary" href="#/settings">Back to Profile</Button>}
    />
  );

  return <ConfirmEmailSuccess target={target} />;
}

function ConfirmEmailSuccess({ target }) {
  const ctx = useRoles();
  const [applied, setApplied] = uAu(false);
  React.useEffect(() => {
    if (applied) return;
    ctx.completeEmailChange(ctx.actor.id);
    setApplied(true);
  }, [applied]);

  return (
    <AuthOutcome
      tone="ok" icon="mail-check"
      title="Email address confirmed"
      body={"You'll sign in with " + target + " from now on. Your password and everything else stay the same."}
      note="We've let your previous address know the change is complete."
      actions={<Button variant="primary" href="#/settings">Back to Profile</Button>}
    />
  );
}

/* =====================================================================
   Sign in — reached from the invitation outcome screens
   ===================================================================== */
function SignInScreen() {
  const S = window.MP_SSO;
  if (S) S.useSso();
  const [emergency, setEmergency] = uAu(false);
  const required = S ? S.isRequired() : false;
  const optional = S ? S.isActive() && !required : false;
  const Continue = window.SsoContinueButton;

  const passwordForm = (
    <>
      <div className="mp-field">
        <label className="mp-field-label">Email</label>
        <input className="mp-field-input" type="email" placeholder="name@company.co.uk" />
      </div>
      <div className="mp-field">
        <label className="mp-field-label">Password</label>
        <input className="mp-field-input" type="password" placeholder="••••••••" />
      </div>
      <Button variant={required ? "secondary" : "primary"} size="lg" href="#/dashboard">Sign In</Button>
    </>);

  return (
    <AuthShell>
      <h1 className="mp-auth-title">Sign In</h1>
      <p className="mp-auth-body">Welcome back.</p>
      <div className="mp-auth-form">
        {required ?
        <>
          {Continue ? <Continue primary /> : null}
          {emergency ?
            <div className="mp-sso-emergency">
              <p className="mp-sso-emergency-note">Emergency access is for the Account Owner only.</p>
              {passwordForm}
            </div> :
            <button type="button" className="mp-sso-emergency-link" onClick={() => setEmergency(true)}>Account Owner emergency access</button>}
        </> :
        <>
          {passwordForm}
          {optional ?
          <>
            <div className="mp-auth-divider"><span>or</span></div>
            {Continue ? <Continue /> : null}
          </> : null}
        </>}
      </div>
    </AuthShell>
  );
}

Object.assign(window, {
  AuthShell, AuthOutcome, AcceptInvitationScreen, AcceptInvitationForm,
  ConfirmEmailScreen, ConfirmEmailSuccess, SignInScreen, INVITE_DEMO
});
