/* Sentinel — access gate: domain-restricted sign-in + email OTP (2FA). */

const ACCOUNTS = {
  "daniel@edencaremedical.com": "head",
  "moss@ginja.ai": "ceo",
  "aisha@edencaremedical.com": "rm",
  "priya@ginja.ai": "admin",
};
const ALLOWED_DOMAINS = ["edencaremedical.com", "ginja.ai"];
const DEMO_CODE = "481920";

function OtpBoxes({ value, onChange }) {
  const refs = React.useRef([]);
  const set = (i, v) => {
    v = v.replace(/\D/g, "").slice(-1);
    const arr = value.split("");
    arr[i] = v; const next = arr.join("").slice(0, 6);
    onChange(next);
    if (v && i < 5) refs.current[i + 1] && refs.current[i + 1].focus();
  };
  const onKey = (i, e) => { if (e.key === "Backspace" && !value[i] && i > 0) refs.current[i - 1] && refs.current[i - 1].focus(); };
  return (
    <div style={{ display: "flex", gap: 9, justifyContent: "center" }}>
      {[0, 1, 2, 3, 4, 5].map((i) => (
        <input key={i} ref={(el) => (refs.current[i] = el)} value={value[i] || ""} onChange={(e) => set(i, e.target.value)} onKeyDown={(e) => onKey(i, e)}
          inputMode="numeric" maxLength={1} style={{ width: 46, height: 56, textAlign: "center", fontFamily: "var(--font-mono)", fontSize: 22, fontWeight: 600,
            border: "1px solid var(--border-strong)", borderRadius: "var(--radius-md)", background: "var(--bg-surface)", color: "var(--content-strong)", outlineColor: "var(--ec-ring)" }} />
      ))}
    </div>
  );
}

function LoginScreen({ onAuthed }) {
  const [step, setStep] = React.useState("email");
  const [email, setEmail] = React.useState("");
  const [otp, setOtp] = React.useState("");
  const [err, setErr] = React.useState("");
  const [sent, setSent] = React.useState(false);

  const domainOk = (e) => ALLOWED_DOMAINS.includes((e.split("@")[1] || "").toLowerCase());
  const submitEmail = () => {
    if (!email.includes("@") || !domainOk(email)) { setErr("Access is restricted to @edencaremedical.com and @ginja.ai accounts."); return; }
    setErr(""); setSent(true); setStep("otp");
  };
  const verify = () => {
    if (otp !== DEMO_CODE) { setErr("That code didn't match. Use the demo code shown below."); return; }
    const role = ACCOUNTS[email.toLowerCase()] || "head";
    onAuthed(role, email.toLowerCase());
  };

  return (
    <div className="ginja-root" style={{ height: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: "var(--bg-page)", position: "relative", overflow: "hidden" }}>
      {/* brand wash */}
      <div style={{ position: "absolute", inset: 0, background: "radial-gradient(60% 50% at 50% 0%, var(--green-50), transparent 70%)", opacity: 0.7 }} />
      <div style={{ position: "relative", width: 420, maxWidth: "92vw" }}>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", marginBottom: 22 }}>
          <img src="assets/logo.svg" alt="Ginja·Ai" style={{ height: 30, marginBottom: 14 }} />
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--content-muted)", border: "1px solid var(--border-base)", borderRadius: 5, padding: "3px 9px" }}>Sentinel · Contract Review</span>
        </div>

        <Card padding={28}>
          {step === "email" ? (
            <>
              <div style={{ fontSize: 20, fontWeight: 600, color: "var(--content-strong)", marginBottom: 4 }}>Sign in</div>
              <div style={{ fontSize: 13.5, color: "var(--content-muted)", marginBottom: 20 }}>Use your Eden Care or Ginja.Ai work email. We'll send a one-time code.</div>
              <Field label="Work email">
                <Input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@edencaremedical.com" type="email"
                  onKeyDown={(e) => e.key === "Enter" && submitEmail()} />
              </Field>
              {err && <div style={{ fontSize: 13, color: "var(--status-danger)", marginTop: 8, display: "flex", alignItems: "center", gap: 6 }}><Icon name="alert-circle" size={14} />{err}</div>}
              <Button leadingIcon="mail" onClick={submitEmail} style={{ width: "100%", marginTop: 18, justifyContent: "center" }}>Send one-time code</Button>
              <div style={{ marginTop: 20, paddingTop: 16, borderTop: "1px solid var(--border-subtle)" }}>
                <div className="text-label" style={{ marginBottom: 9 }}>Demo accounts — tap to fill</div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 7 }}>
                  {Object.entries(ACCOUNTS).map(([e, r]) => (
                    <button key={e} onClick={() => { setEmail(e); setErr(""); }} style={{ display: "flex", alignItems: "center", gap: 8, padding: "8px 10px", border: "1px solid var(--border-base)", borderRadius: "var(--radius-md)", background: "var(--bg-surface)", cursor: "pointer", textAlign: "left", fontFamily: "var(--font-body)" }}
                      onMouseEnter={(ev) => (ev.currentTarget.style.background = "var(--bg-sunken)")} onMouseLeave={(ev) => (ev.currentTarget.style.background = "var(--bg-surface)")}>
                      <Avatar name={ROLES[r].name} size={26} tone={ROLES[r].tone} />
                      <span style={{ minWidth: 0 }}><span style={{ display: "block", fontSize: 12.5, fontWeight: 600, color: "var(--content-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{ROLES[r].title}</span>
                        <span style={{ display: "block", fontSize: 11, color: "var(--content-muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{e}</span></span>
                    </button>
                  ))}
                </div>
              </div>
            </>
          ) : (
            <>
              <button onClick={() => { setStep("email"); setOtp(""); setErr(""); }} style={{ display: "inline-flex", alignItems: "center", gap: 5, background: "none", border: "none", color: "var(--content-muted)", cursor: "pointer", fontFamily: "var(--font-body)", fontSize: 13, padding: 0, marginBottom: 14 }}><Icon name="arrow-left" size={14} />Back</button>
              <div style={{ fontSize: 20, fontWeight: 600, color: "var(--content-strong)", marginBottom: 4 }}>Enter your code</div>
              <div style={{ fontSize: 13.5, color: "var(--content-muted)", marginBottom: 20 }}>We sent a 6-digit code to <strong style={{ color: "var(--content-strong)" }}>{email}</strong>. It expires in 10 minutes.</div>
              <OtpBoxes value={otp} onChange={(v) => { setOtp(v); setErr(""); }} />
              {err && <div style={{ fontSize: 13, color: "var(--status-danger)", marginTop: 12, textAlign: "center", display: "flex", alignItems: "center", justifyContent: "center", gap: 6 }}><Icon name="alert-circle" size={14} />{err}</div>}
              <Button leadingIcon="shield-check" onClick={verify} disabled={otp.length !== 6} style={{ width: "100%", marginTop: 18, justifyContent: "center", opacity: otp.length !== 6 ? 0.55 : 1, cursor: otp.length !== 6 ? "not-allowed" : "pointer" }}>Verify & sign in</Button>
              <div style={{ marginTop: 16, padding: "10px 12px", background: "var(--bg-sunken)", borderRadius: "var(--radius-md)", display: "flex", alignItems: "center", gap: 9, fontSize: 12.5, color: "var(--content-muted)" }}>
                <Icon name="smartphone" size={15} /> Demo code: <span className="text-mono" style={{ fontWeight: 600, color: "var(--content-strong)", letterSpacing: "0.1em" }}>{DEMO_CODE}</span>
                <button onClick={() => setOtp(DEMO_CODE)} style={{ marginLeft: "auto", background: "none", border: "none", color: "var(--ec-link)", cursor: "pointer", fontFamily: "var(--font-body)", fontSize: 12.5, fontWeight: 600, textDecoration: "underline" }}>Autofill</button>
              </div>
            </>
          )}
        </Card>
        <div style={{ textAlign: "center", marginTop: 16, fontSize: 12, color: "var(--content-faint)", display: "flex", alignItems: "center", justifyContent: "center", gap: 6 }}>
          <Icon name="lock" size={12} /> Domain-restricted · OTP 2FA on every login · all activity audited
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { LoginScreen, ACCOUNTS });
