// shared.jsx - reusable site bits: waitlist form, store badges, interactive bisou.
(function () {
  const { Button, KissMark } = window.BisouxDesignSystem_144cac;
  const Ic = window.BxIcon;

  // The signature gesture, made interactive. Click and the disc presses in and
  // blooms, a ring ripples outward, and a kiss floats up - one-shot, on-brand.
  // Restart is done by direct reflow so the animation replays on every click.
  function BisouTap({ size = 96, idleKiss = "red", hint }) {
    const ref = React.useRef(null);
    const send = () => {
      const el = ref.current;
      if (!el) return;
      el.classList.remove("sent");
      void el.offsetWidth; // force reflow → restart the keyframes
      el.classList.add("sent");
    };
    return (
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 10 }}>
        <button ref={ref} className="bisou-tap" style={{ width: size, height: size }}
          onClick={send} aria-label="Send a bisou">
          <span className="bisou-ring"></span>
          <span className="bisou-disc"><KissMark tone={idleKiss} size={Math.round(size * 0.46)} /></span>
          <span className="bisou-fly"><KissMark tone="red" size={Math.round(size * 0.34)} /></span>
        </button>
        {hint ? (
          <span style={{ fontSize: 12, color: "var(--text-secondary)", background: "var(--surface)", border: "1px solid var(--border)", padding: "5px 12px", borderRadius: 999, whiteSpace: "nowrap" }}>
            {hint}
          </span>
        ) : null}
      </div>
    );
  }

  // Inline waitlist - calm, single field + one accent button. Confirmation is
  // plain and reassuring, in the Bisoux voice. No exclamation marks.
  // Saves to Supabase (waitlist table, insert-only RLS) when credentials are
  // set in site/config.js; until then it falls back to the front-end mock.
  function Waitlist({ light, compact }) {
    const [email, setEmail] = React.useState("");
    const [done, setDone] = React.useState(false);
    const [busy, setBusy] = React.useState(false);
    const [err, setErr] = React.useState(false);
    const valid = /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email);

    async function submit(e) {
      e.preventDefault();
      if (!valid || busy) return;
      const cfg = window.BX_CONFIG || {};
      if (!cfg.supabaseUrl || !cfg.supabaseAnonKey) { setDone(true); return; }
      setBusy(true);
      setErr(false);
      try {
        const res = await fetch(cfg.supabaseUrl.replace(/\/+$/, "") + "/rest/v1/waitlist", {
          method: "POST",
          headers: {
            // apikey alone is the documented path for sb_publishable_ keys;
            // the gateway runs the request as the anon role.
            apikey: cfg.supabaseAnonKey,
            "Content-Type": "application/json",
            Prefer: "return=minimal",
          },
          body: JSON.stringify({ email: email.trim().toLowerCase() }),
        });
        // 409 = unique-constraint conflict: already on the list. Same outcome.
        if (res.ok || res.status === 409) setDone(true);
        else setErr(true);
      } catch (e2) {
        setErr(true);
      }
      setBusy(false);
    }

    if (done) {
      return (
        <div className="reveal in" style={{ display: "flex", alignItems: "center", gap: 12, padding: "14px 18px", border: "1px solid var(--border)", borderRadius: 999, background: "var(--surface)", maxWidth: 460 }}>
          <span style={{ width: 30, height: 30, borderRadius: 999, background: "var(--accent-soft)", color: "var(--accent)", display: "inline-flex", alignItems: "center", justifyContent: "center", flex: "0 0 auto" }}>
            <Ic.check size={18} />
          </span>
          <span style={{ fontSize: 15, color: "var(--text)" }}>
            You're on the list. We'll write the moment there's room for you two.
          </span>
        </div>
      );
    }

    return (
      <form
        className="waitlist-form"
        style={{ maxWidth: compact ? 480 : 520 }}
        onSubmit={submit}
      >
        <div className="field" style={{ position: "relative" }}>
          <span style={{ position: "absolute", left: 18, top: "50%", transform: "translateY(-50%)", color: "var(--text-secondary)", pointerEvents: "none" }}>
            <Ic.mail size={19} />
          </span>
          <input
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="you@yours.com"
            aria-label="Your email"
            style={{
              width: "100%", height: 54, padding: "0 18px 0 48px",
              fontFamily: "var(--font-body)", fontSize: 16, color: "var(--text)",
              background: light ? "rgba(244,239,229,0.92)" : "var(--surface)",
              border: "1px solid var(--border)", borderRadius: 999, outline: "none",
              transition: "border-color 200ms var(--motion-ease), box-shadow 200ms var(--motion-ease)",
            }}
            onFocus={(e) => { e.target.style.borderColor = "var(--accent)"; e.target.style.boxShadow = "0 0 0 3px var(--accent-soft)"; }}
            onBlur={(e) => { e.target.style.borderColor = "var(--border)"; e.target.style.boxShadow = "none"; }}
          />
        </div>
        <Button variant="primary" size="lg" type="submit" disabled={busy} style={{ height: 54, whiteSpace: "nowrap", opacity: busy ? 0.7 : 1 }}>
          {busy ? "Joining" : "Join the waitlist"}
        </Button>
        {err ? (
          <p role="alert" style={{ flexBasis: "100%", margin: "6px 4px 0", fontSize: 13.5, color: "var(--accent)" }}>
            Something quiet went wrong. Please try again in a moment.
          </p>
        ) : null}
      </form>
    );
  }

  function StoreBadges() {
    return (
      <div className="btn-row">
        <div className="store-badge" role="button" tabIndex={0} data-magnetic="0.3">
          <Ic.apple size={24} />
          <span><span className="sb-top">Coming soon to</span><br /><span className="sb-bot">App Store</span></span>
        </div>
        <div className="store-badge" role="button" tabIndex={0} data-magnetic="0.3">
          <Ic.play size={22} />
          <span><span className="sb-top">Coming soon to</span><br /><span className="sb-bot">Google Play</span></span>
        </div>
      </div>
    );
  }

  Object.assign(window, { BxWaitlist: Waitlist, BxStoreBadges: StoreBadges, BxBisouTap: BisouTap });
})();
