// ===========================================================
// InviteFriend: the signed-in member's "invite a friend" sheet.
// Reuses the av2-backdrop/av2-modal overlay (so on mobile it is the
// full-cover, body-scroll-locked layer the collection uses post-fix,
// and a centred card on desktop), NOT a floating panel.
//
// Sharing is the device's native share sheet (navigator.share) with a
// copy-link control as the universal fallback. No attribution, no token:
// the invite link is a single public URL that leads to the sign-up pitch.
// ===========================================================
const { useState: useInvState, useEffect: useInvEffect, useRef: useInvRef } = React;

// Single clean shareable URL. /collection?invite=1 lands a logged-out
// visitor on the "start your own collection" pitch (MarketingSurface),
// and a signed-in visitor straight on their own collection. ?invite=1
// only tailors the landing copy; it carries no identity.
const BBR_INVITE_URL = "https://www.theleadin.com/collection?invite=1";
// Locked share text (the URL follows it).
const BBR_INVITE_TEXT = "I track my vinyl on The Lead-In. Start yours:";

function InviteFriend({ onClose }) {
  const canShare = typeof navigator !== "undefined" && typeof navigator.share === "function";
  const [copied, setCopied] = useInvState(false);
  const urlRef = useInvRef(null);
  const copyTimer = useInvRef(0);
  // Hold the latest onClose so the history effect can run once (empty deps)
  // without re-pushing a state every time the parent re-renders a fresh onClose.
  const onCloseRef = useInvRef(onClose);
  onCloseRef.current = onClose;

  // Lock the page behind the overlay. Plain overflow:hidden on body is
  // ignored by iOS Safari (the page still pans, dragging the fixed layer),
  // so pin the body with position:fixed at -scrollY and restore on close.
  // Same pattern as MyCollectionAdd_v2; the parent mounts this only while open.
  useInvEffect(() => {
    const scrollY = window.scrollY || window.pageYOffset || 0;
    const b = document.body;
    const prev = {
      position: b.style.position, top: b.style.top, left: b.style.left,
      right: b.style.right, width: b.style.width, overflow: b.style.overflow,
    };
    b.style.position = "fixed";
    b.style.top = "-" + scrollY + "px";
    b.style.left = "0";
    b.style.right = "0";
    b.style.width = "100%";
    b.style.overflow = "hidden";
    return () => {
      b.style.position = prev.position; b.style.top = prev.top;
      b.style.left = prev.left; b.style.right = prev.right;
      b.style.width = prev.width; b.style.overflow = prev.overflow;
      window.scrollTo(0, scrollY);
    };
  }, []);

  // D-NAV-01: give the mobile back gesture something to pop so it closes the
  // sheet instead of navigating the SPA to home. Push one history entry on open
  // keeping the URL unchanged (same path+search+hash), so App.jsx's global
  // popstate re-parses to the same route and stays a no-op. Run once on open.
  useInvEffect(() => {
    const url = location.pathname + location.search + location.hash;
    history.pushState({ bbrInvite: true }, "", url);
    // Set when the back gesture pops our entry, so cleanup knows the browser
    // already consumed it and must not pop again (the double-pop guard).
    let popped = false;
    const onPop = () => { popped = true; onCloseRef.current(); };
    window.addEventListener("popstate", onPop);
    return () => {
      window.removeEventListener("popstate", onPop);
      // Closed by a non-back path (backdrop / close x / Escape): our pushed
      // entry is still on the stack, so consume it once. If the back gesture
      // closed us, popped is true and the browser already removed it.
      if (!popped) history.back();
    };
  }, []);

  // Esc closes, matching the other overlays' dismiss-friendliness.
  useInvEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  useInvEffect(() => () => { if (copyTimer.current) clearTimeout(copyTimer.current); }, []);

  async function doShare() {
    // Opens the OS share sheet; the user picks WhatsApp / Messages / Mail /
    // socials from their own apps. A cancelled share rejects (AbortError) and
    // must be swallowed silently, so any throw here is a no-op.
    try {
      await navigator.share({ title: "The Lead-In", text: BBR_INVITE_TEXT, url: BBR_INVITE_URL });
    } catch (e) { /* user cancelled or share unavailable: say nothing */ }
  }

  async function doCopy() {
    if (copyTimer.current) clearTimeout(copyTimer.current);
    try {
      await navigator.clipboard.writeText(BBR_INVITE_URL);
      setCopied(true);
      copyTimer.current = setTimeout(() => setCopied(false), 2200);
    } catch (e) {
      // Clipboard blocked: select the text so the user can copy it manually.
      if (urlRef.current) { urlRef.current.focus(); urlRef.current.select(); }
    }
  }

  return (
    <div className="av2-backdrop" onClick={onClose}>
      <div className="av2-modal inv-modal" onClick={(e) => e.stopPropagation()}>
        <div className="av2-head">
          <div className="av2-head-left">
            <button className="av2-back-arrow" aria-label="Back to collection" onClick={onClose}>
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M12 4l-5 6 5 6" /></svg>
            </button>
            <span className="av2-head-title">Invite a friend</span>
          </div>
          <button className="av2-x" aria-label="Close" onClick={onClose}>×</button>
        </div>
        <div className="av2-body">
          <div className="inv-pane">
            <p className="inv-lede">Share The Lead-In so a friend can start their own collection.</p>

            {canShare && (
              <button className="inv-share" onClick={doShare}>
                <svg width="17" height="17" viewBox="0 0 18 18" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                  <circle cx="13.5" cy="3.8" r="2.3" /><circle cx="4.5" cy="9" r="2.3" /><circle cx="13.5" cy="14.2" r="2.3" />
                  <path d="M6.5 7.8l5 -2.8M6.5 10.2l5 2.8" />
                </svg>
                Share
              </button>
            )}

            <div className="inv-copy">
              <div className="inv-copy-label">Or copy the link</div>
              <div className="inv-copy-row">
                <input
                  ref={urlRef} className="inv-copy-url" type="text" readOnly
                  value={BBR_INVITE_URL}
                  onFocus={(e) => e.target.select()}
                  onClick={(e) => e.target.select()}
                  aria-label="Invite link"
                />
                <button className={"inv-copy-btn" + (copied ? " done" : "")} onClick={doCopy}>
                  {copied ? "Copied" : "Copy"}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { InviteFriend, BBR_INVITE_URL });
