// VELOUR — member sign-in, by magic link.
//
// One field and one button. Signing up and signing in are the same act here: there
// is no separate registration step, so there is no wrong door to pick and no
// password to invent, forget or reset.
//
// The session itself lives in window.velourAuth (src/_ds_bundle.js) so web and
// mobile share one implementation — they are one origin and one session.
//
// This screen proves nothing on its own. Every request that matters is re-checked
// server-side against the token; treat what renders here as convenience.
const { Button } = window.VelourDesignSystem_380ed4;

function SignInOverlay({ open, onClose }) {
  const [email, setEmail] = React.useState("");
  const [state, setState] = React.useState("idle"); // idle | sending | sent | error | unknown
  const [error, setError] = React.useState(null);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    setState("idle"); setError(null);
    const t = setTimeout(() => inputRef.current && inputRef.current.focus(), 60);
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    return () => { clearTimeout(t); document.removeEventListener("keydown", onKey); };
  }, [open]);

  if (!open) return null;

  const send = () => {
    if (state === "sending") return;
    setState("sending"); setError(null);
    window.velourAuth.sendLink(email)
      .then(() => setState("sent"))
      .catch((e) => {
        if (e && e.code === "unknown_email") { setState("unknown"); return; }
        setError(e.message || "That link couldn't be sent just now."); setState("error");
      });
  };

  const beginInstead = () => {
    onClose();
    // window.velourOpenSignup (site.jsx) already knows to jump to the fresh
    // entry when it isn't on it — the exact routing this panel needs, now
    // shared with every other "Begin" button on the site rather than
    // duplicated here.
    window.velourOpenSignup && window.velourOpenSignup();
  };

  const field = { width: "100%", padding: "13px 15px", borderRadius: 12, border: "var(--border-width) solid var(--border)", background: "var(--surface-card)", fontFamily: "var(--font-sans)", fontSize: 15, color: "var(--text-primary)", outline: "none", boxSizing: "border-box" };

  return (
    <div role="dialog" aria-modal="true" aria-label="Sign in to VELOUR"
      style={{ position: "fixed", inset: 0, background: "rgba(28,28,26,0.42)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 60, padding: 24 }}
      onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()}
        style={{ width: 420, maxWidth: "100%", background: "var(--surface-card)", borderRadius: 20, padding: 30, boxShadow: "var(--shadow-xl)" }}>

        {state === "sent" ? (
          <React.Fragment>
            <div style={{ fontFamily: "var(--font-serif)", fontSize: 24, color: "var(--text-primary)", letterSpacing: "-0.01em", marginBottom: 10 }}>Check your email.</div>
            <p style={{ fontSize: 14.5, color: "var(--text-secondary)", lineHeight: 1.6, margin: "0 0 20px" }}>
              A sign-in link is on its way to <span style={{ color: "var(--text-primary)" }}>{email}</span>. Open it on this device and you'll be signed in — there's no password to remember.
            </p>
            <p style={{ fontSize: 13, color: "var(--text-tertiary)", lineHeight: 1.55, margin: "0 0 22px" }}>
              The link works once and expires after an hour. If it doesn't arrive, check the spam folder before asking for another.
            </p>
            <Button size="sm" onClick={onClose}>Done</Button>
          </React.Fragment>
        ) : state === "unknown" ? (
          <React.Fragment>
            <div style={{ fontFamily: "var(--font-serif)", fontSize: 24, color: "var(--text-primary)", letterSpacing: "-0.01em", marginBottom: 10 }}>No account yet.</div>
            <p style={{ fontSize: 14.5, color: "var(--text-secondary)", lineHeight: 1.6, margin: "0 0 22px" }}>
              There's no VELOUR account for <span style={{ color: "var(--text-primary)" }}>{email}</span>. Begin sets up your first ritual and creates one — it takes under a minute.
            </p>
            <div style={{ display: "flex", gap: 10, alignItems: "center" }}>
              <Button size="sm" onClick={beginInstead}>Begin</Button>
              <button onClick={() => setState("idle")} style={{ background: "none", border: "none", color: "var(--text-secondary)", fontFamily: "var(--font-sans)", fontSize: 14, cursor: "pointer" }}>Try another address</button>
            </div>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <div style={{ fontFamily: "var(--font-serif)", fontSize: 24, color: "var(--text-primary)", letterSpacing: "-0.01em", marginBottom: 8 }}>Sign in to VELOUR</div>
            <p style={{ fontSize: 14.5, color: "var(--text-secondary)", lineHeight: 1.6, margin: "0 0 20px" }}>
              Enter your email and we'll send a link. No password to create, and none to forget.
            </p>

            <label htmlFor="vlr-signin-email" style={{ fontSize: 11.5, letterSpacing: "0.04em", color: "var(--text-tertiary)", marginBottom: 6, display: "block" }}>Email</label>
            <input id="vlr-signin-email" ref={inputRef} type="email" autoComplete="email" value={email}
              onChange={(e) => setEmail(e.target.value)}
              onKeyDown={(e) => { if (e.key === "Enter") send(); }}
              placeholder="you@example.com" style={field} />

            {error && (
              <div style={{ display: "flex", gap: 9, alignItems: "flex-start", marginTop: 14, fontSize: 13.5, color: "var(--text-secondary)", lineHeight: 1.5 }}>
                <i className="ph ph-warning-circle" style={{ fontSize: 16, color: "var(--terracotta, var(--text-tertiary))", marginTop: 1 }}></i>
                <span>{error}</span>
              </div>
            )}

            <div style={{ display: "flex", gap: 10, marginTop: 22, alignItems: "center" }}>
              <Button size="sm" onClick={send} disabled={state === "sending" || !email.trim()}>
                {state === "sending" ? "Sending…" : "Send the link"}
              </Button>
              <button onClick={onClose} style={{ background: "none", border: "none", color: "var(--text-secondary)", fontFamily: "var(--font-sans)", fontSize: 14, cursor: "pointer" }}>Not now</button>
            </div>

            <p style={{ fontSize: 12, color: "var(--text-tertiary)", lineHeight: 1.55, margin: "20px 0 0" }}>
              Everything you've already added on this device stays where it is. Signing in is how it starts travelling with you.
            </p>
          </React.Fragment>
        )}
      </div>
    </div>
  );
}

window.SignInOverlay = SignInOverlay;
