// Login screen — cute, gentle, secret question.
const { useState, useEffect, useRef } = React;

function Petals() {
  const petals = React.useMemo(() => {
    return Array.from({length: 14}, (_, i) => ({
      left: Math.random() * 100,
      delay: -Math.random() * 18,
      duration: 14 + Math.random() * 12,
      size: 8 + Math.random() * 12,
      hue: Math.random() * 18 - 9,
    }));
  }, []);
  return (
    <>
      {petals.map((p, i) => (
        <span
          key={i}
          className="petal"
          style={{
            left: p.left + "%",
            top: 0,
            width: p.size,
            height: p.size,
            animationDelay: p.delay + "s",
            animationDuration: p.duration + "s",
            filter: `hue-rotate(${p.hue}deg)`,
          }}
        />
      ))}
    </>
  );
}

function Login({ onPass }) {
  const [val, setVal] = useState("");
  const [shake, setShake] = useState(false);
  const [showHint, setShowHint] = useState(false);
  const inputRef = useRef(null);

  useEffect(() => { inputRef.current?.focus(); }, []);

  function submit(e) {
    e?.preventDefault();
    const normalized = val.trim().toLowerCase().replace(/[^a-z0-9]/g, "");
    if (normalized.includes("nuldum")) {
      onPass();
    } else {
      setShake(true);
      setTimeout(() => setShake(false), 500);
    }
  }

  return (
    <div className="login-stage" data-screen-label="01 Login">
      <Petals />
      <form className="login-card" onSubmit={submit}>
        <div className="login-stamp">Karen only</div>
        <div className="login-heart">♥</div>
        <h1 className="login-title">For you, Karen.</h1>
        <p className="login-q">where did we first meet?</p>
        <input
          ref={inputRef}
          className={"login-input" + (shake ? " shake" : "")}
          value={val}
          onChange={(e) => setVal(e.target.value)}
          placeholder="answer…"
          autoComplete="off"
          spellCheck="false"
        />
        <button type="submit" className="login-btn">open</button>
        <p className="login-hint" onClick={() => setShowHint(true)}>
          {showHint
            ? <>hint: <b>a coffee shop on orchard</b> ☕</>
            : <>can't remember? <b>hint</b></>}
        </p>
      </form>
    </div>
  );
}

window.Login = Login;
