// Gate.jsx — retailer passcode gate, in the lookbook's voice: ONE full-bleed
// cover image, the display headline over it, and a minimal login line at the
// bottom. Copy + image live in settings (gate* keys) — editable from admin ›
// settings AND directly on the page in ?edit=1 (EditBar › ◫ gate).

function Gate({ onEnter, content, looksCount, season, editable }) {
  const ec = React.useContext(window.EditCtx) || {};
  const edit = !!(editable && ec.edit && !ec.preview);
  const [code, setCode] = React.useState("");
  const [name, setName] = React.useState("");
  const [error, setError] = React.useState("");
  const [shake, setShake] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);

  const c = content || {};
  const image    = c.image || "";
  const heroA    = c.heroA || "a quiet body.";
  const heroB    = c.heroB || "cut from concrete light.";
  const location = c.location || "ATELIER · KYOTO";
  const label    = c.label || "ENTER · WHOLESALE";
  const intro    = c.intro || "this room holds the collection. enter your retailer passcode below.";
  const button   = c.button || "enter the room";
  const save = (key) => (v) => ec.saveSetting && ec.saveSetting({ [key]: v });

  // Cover reframe (edit mode): the same pan/zoom transform box as look covers,
  // stored PER DEVICE in settings.gateImageTf ({desktop:{x,y,s}, mobile:{…}};
  // a legacy flat {x,y,s} counts as desktop). Mobile falls back to desktop.
  // Editing follows the edit bar's device toggle; retailers get their viewport's.
  const [mob, setMob] = React.useState(() =>
    typeof window !== "undefined" && window.matchMedia && window.matchMedia("(max-width: 900px)").matches);
  React.useEffect(() => {
    if (!window.matchMedia) return;
    const mq = window.matchMedia("(max-width: 900px)");
    const f = () => setMob(mq.matches);
    mq.addEventListener ? mq.addEventListener("change", f) : mq.addListener(f);
    window.addEventListener("resize", f);
    return () => {
      mq.removeEventListener ? mq.removeEventListener("change", f) : mq.removeListener(f);
      window.removeEventListener("resize", f);
    };
  }, []);
  const device = edit ? (ec.device || "desktop") : (mob ? "mobile" : "desktop");
  const rawTf = c.imageTf || null;
  const legacyFlat = rawTf && rawTf.x != null ? rawTf : null;
  const savedTf = (rawTf && rawTf[device]) || (device === "mobile" && rawTf && rawTf.desktop) || legacyFlat
    || (rawTf && rawTf.desktop) || { x: 50, y: 50, s: 1 };
  const [tfPrev, setTfPrev] = React.useState(null);
  const tfKey = JSON.stringify([savedTf, device]);
  React.useEffect(() => { setTfPrev(null); }, [tfKey]);
  const tf = tfPrev || savedTf;
  const commitTf = (ntf) => {
    setTfPrev(ntf);
    save("gateImageTf")({ ...(legacyFlat ? { desktop: legacyFlat } : (rawTf || {})), [device]: ntf });
  };

  const submit = async (e) => {
    e && e.preventDefault();
    if (editable) return;   // the edit-mode copy of the page never signs in
    const trimmed = code.trim().toUpperCase();
    if (!trimmed) {
      setError("a passcode is required.");
      setShake(true); setTimeout(() => setShake(false), 400);
      return;
    }
    setSubmitting(true);
    try {
      const { retailer } = await window.api.post("/api/auth", { code: trimmed, name: name.trim() });
      onEnter(retailer);
    } catch (err) {
      setError(err.message || "could not enter.");
      setShake(true); setTimeout(() => setShake(false), 400);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className={"gate2" + (image ? "" : " is-bare")} data-screen-label="00 Gate">
      <div className="gate2-media" {...(edit ? window.dropProps(ec, (p) => save("gateImage")(p)) : {})}>
        {image && (
          <img className="gate2-img" alt="" draggable={false}
            src={window.sbImg ? window.sbImg(image, 2000) : image}
            srcSet={window.sbSrcSet ? window.sbSrcSet(image) : undefined} sizes="100vw"
            style={{
              objectPosition: tf.x + "% " + tf.y + "%",
              transform: "scale(" + tf.s + ")",
              transformOrigin: tf.x + "% " + tf.y + "%",
            }} />
        )}
        {edit && image && (
          <window.SBTransformBox tf={tf}
            onChange={(ntf) => setTfPrev(ntf)}
            onCommit={commitTf} />
        )}
        {edit && <window.EditableImage title="⤓ cover image · or drop a file" onPick={(p) => save("gateImage")(p)} />}
      </div>
      <div className="gate2-scrim" />

      <header className="gate2-top">
        <span className="gate2-wm">subtlebody</span>
        <span className="gate2-meta">
          {season || "FW·26"} · <window.EditableText tag="span" value={location} onSave={save("gateLocation")} />
          {looksCount ? <span className="dim2">  ·  {String(looksCount).padStart(2, "0")} LOOKS</span> : null}
        </span>
      </header>

      <div className="gate2-low">
        <h1 className="gate2-hero">
          <window.EditableText tag="span" value={heroA} onSave={save("gateHeroA")} />{" "}
          <em><window.EditableText tag="span" value={heroB} onSave={save("gateHeroB")} /></em>
        </h1>

        <form className={"gate2-login" + (shake ? " is-shake" : "")} onSubmit={submit}
          style={shake ? { animation: "gate2shake 360ms" } : null}>
          <span className="gate2-label">[ <window.EditableText tag="span" value={label} onSave={save("gateLabel")} /> ]</span>
          <p className="gate2-intro">
            <window.EditableText tag="span" multiline value={intro} onSave={save("gateIntro")} />
          </p>
          <div className="gate2-fields">
            <input className="gate2-input" type="text" placeholder="retailer"
              aria-label="retailer name" value={name} onChange={(e) => setName(e.target.value)} />
            <input className="gate2-input gate2-code" type="text" placeholder="passcode" autoComplete="off"
              aria-label="passcode" value={code} onChange={(e) => { setCode(e.target.value); setError(""); }} />
            <button type="submit" className="gate2-enter" disabled={submitting}>
              {submitting ? "entering…" : <React.Fragment><window.EditableText tag="span" value={button} onSave={save("gateButton")} /> ⟶</React.Fragment>}
            </button>
          </div>
          {error && <div className="gate2-error">— {error}</div>}
        </form>
      </div>
      <style>{`
        @keyframes gate2shake {
          0%, 100% { transform: translateX(0); }
          25% { transform: translateX(-6px); }
          50% { transform: translateX(6px); }
          75% { transform: translateX(-3px); }
        }
      `}</style>
    </div>
  );
}

window.Gate = Gate;
