/* engagement.jsx — Dynamic tab title + Exit-intent overlay */

const CHECKOUT_URL_EI = "https://checkout.theborntoknow.com/checkout/buy/8edcc250-1c08-4dd6-a88a-a0081454cc63";

/* ── Tab title messages ─────────────────────────────── */
const AWAY_TITLES = [
  "👀 Still thinking? · The Baby Blueprint",
  "⏳ Launch price ends at 1,000 copies",
  "🧠 Your baby's brain won't wait forever",
  "💡 108 pages that finally make sense",
  "👶 Come back - $23.95 launch price",
];
const HOME_TITLE = "The Baby Blueprint - Understand Your Baby's Brain & Behavior (0-36 mo)";

function DynamicTabTitle() {
  const awayIdx = React.useRef(0);
  const intervalRef = React.useRef(null);

  React.useEffect(() => {
    const onHide = () => {
      if (document.hidden) {
        // Start rotating away messages every 5 seconds
        const rotate = () => {
          document.title = AWAY_TITLES[awayIdx.current % AWAY_TITLES.length];
          awayIdx.current += 1;
        };
        rotate();
        intervalRef.current = setInterval(rotate, 5000);
      } else {
        // User came back — restore title
        clearInterval(intervalRef.current);
        awayIdx.current = 0;
        document.title = HOME_TITLE;
      }
    };

    document.addEventListener("visibilitychange", onHide);
    return () => {
      document.removeEventListener("visibilitychange", onHide);
      clearInterval(intervalRef.current);
      document.title = HOME_TITLE;
    };
  }, []);

  return null;
}

/* ── Exit-intent overlay ────────────────────────────── */
function ExitIntentOverlay() {
  const [visible, setVisible] = React.useState(false);
  const shown = React.useRef(false);
  const pageLoadTime = React.useRef(Date.now());

  const show = () => {
    if (shown.current) return;
    if (sessionStorage.getItem("btk_exit_shown")) return;
    // Don't show before 45s on page
    if (Date.now() - pageLoadTime.current < 45000) return;
    shown.current = true;
    sessionStorage.setItem("btk_exit_shown", "1");
    setVisible(true);
    document.body.style.overflow = "hidden";
    document.documentElement.style.overflow = "hidden";
  };

  const hide = () => {
    setVisible(false);
    document.body.style.overflow = "";
    document.documentElement.style.overflow = "";
  };

  React.useEffect(() => {
    // ── Desktop: mouse moves toward top of viewport (exit intent) ──
    const onMouseMove = (e) => {
      if (e.clientY < 40 && e.movementY < -5) show();
    };

    // ── Mobile: fast upward scroll (back-gesture intent) ──
    let lastY = window.scrollY;
    let lastTime = Date.now();
    const onScroll = () => {
      const now = Date.now();
      const dy = window.scrollY - lastY;
      const dt = now - lastTime;
      // Fast upward scroll: moved up >200px in <250ms
      if (dy < -200 && dt < 250) show();
      lastY = window.scrollY;
      lastTime = now;
    };

    // ── Mobile inactivity: 120s without interaction ──
    let inactivityTimer = null;
    const resetInactivity = () => {
      clearTimeout(inactivityTimer);
      inactivityTimer = setTimeout(show, 120000);
    };
    const inactivityEvents = ["touchstart", "touchmove", "click"];
    inactivityEvents.forEach(ev => window.addEventListener(ev, resetInactivity, { passive: true }));
    resetInactivity();

    document.addEventListener("mousemove", onMouseMove);
    window.addEventListener("scroll", onScroll, { passive: true });

    return () => {
      document.removeEventListener("mousemove", onMouseMove);
      window.removeEventListener("scroll", onScroll);
      inactivityEvents.forEach(ev => window.removeEventListener(ev, resetInactivity));
      clearTimeout(inactivityTimer);
      document.body.style.overflow = "";
      document.documentElement.style.overflow = "";
    };
  }, []);

  if (!visible) return null;

  return (
    <>
      {/* Backdrop — no click-to-close, only X button closes */}
      <div
        style={{
          position: "fixed", inset: 0, zIndex: 9990,
          background: "rgba(15,15,15,0.45)", backdropFilter: "blur(3px)",
        }}
      />

      {/* Slide-in panel */}
      <div style={{
        position: "fixed", bottom: 16, left: "50%", zIndex: 9991,
        transform: "translateX(-50%)",
        width: "min(540px, calc(100vw - 24px))",
        background: "linear-gradient(160deg, #FFFCF5 0%, #F4EDD8 100%)",
        borderRadius: 16,
        border: "1.5px solid #C8A24A",
        boxShadow: "0 32px 80px rgba(15,15,15,0.30), 0 0 0 1px rgba(255,252,245,0.6)",
        padding: "clamp(20px, 4vw, 32px) clamp(16px, 4vw, 28px) clamp(18px, 3vw, 28px)",
        animation: "slideUpExit 380ms cubic-bezier(0.22,0.61,0.36,1)",
        maxHeight: "calc(100dvh - 32px)",
        overflowY: "auto",
      }}>
        {/* Close button */}
        <button
          onClick={hide}
          aria-label="Close"
          style={{
            position: "absolute", top: 14, right: 14,
            width: 32, height: 32, borderRadius: "50%",
            border: "1px solid #E8DFCC", background: "#FAF6EE",
            cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center"
          }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#3D3A33" strokeWidth="2.2" strokeLinecap="round">
            <path d="M18 6L6 18M6 6l12 12"/>
          </svg>
        </button>

        {/* Content */}
        <div style={{ display: "flex", gap: "clamp(12px, 3vw, 18px)", alignItems: "flex-start" }}>
          {/* Brain icon — hidden on very small screens */}
          <div style={{
            flexShrink: 0, width: 48, height: 48, borderRadius: 12,
            background: "linear-gradient(160deg, #34442C, #2C3A24)",
            display: "flex", alignItems: "center", justifyContent: "center",
            boxShadow: "0 8px 20px rgba(44,58,36,0.30)"
          }}>
            <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#E8A92C" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M9.5 2A2.5 2.5 0 0 1 12 4.5v15a2.5 2.5 0 0 1-4.96-.46 2.5 2.5 0 0 1-1.07-3 2.5 2.5 0 0 1 .09-3.14 2.5 2.5 0 0 1 2.44-4.4z"/>
              <path d="M14.5 2A2.5 2.5 0 0 0 12 4.5v15a2.5 2.5 0 0 0 4.96-.46 2.5 2.5 0 0 0 1.07-3 2.5 2.5 0 0 0-.09-3.14A2.5 2.5 0 0 0 14.5 2z"/>
            </svg>
          </div>

          <div style={{ flex: 1, minWidth: 0 }}>
            {/* Eyebrow */}
            <div style={{
              fontFamily: "Inter, sans-serif", fontSize: 10.5,
              letterSpacing: "0.22em", fontWeight: 700,
              color: "#D97757", marginBottom: 6
            }}>
              BEFORE YOU GO
            </div>
            {/* Headline */}
            <h3 style={{
              fontFamily: "'Playfair Display', Georgia, serif",
              fontSize: "clamp(17px, 4vw, 24px)", fontWeight: 800,
              lineHeight: 1.15, letterSpacing: "-0.02em", color: "#0F0F0F",
              marginBottom: 6
            }}>
              The launch price ends at copy 1,000.
            </h3>
            {/* Body */}
            <p style={{
              fontFamily: "Lora, Georgia, serif", fontSize: "clamp(13px, 3vw, 14px)",
              color: "#3D3A33", lineHeight: 1.55, marginBottom: 14
            }}>
              Your baby's brain is building right now — over one million new connections every second. The Blueprint helps you understand what's happening.
            </p>

            {/* Price row */}
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14 }}>
              <span style={{
                fontFamily: "'Playfair Display', serif", fontSize: 15,
                fontWeight: 700, color: "#B85648", textDecoration: "line-through"
              }}>$39</span>
              <span style={{
                fontFamily: "'Playfair Display', serif", fontSize: 32,
                fontWeight: 900, color: "#2C3A24", letterSpacing: "-0.02em", lineHeight: 1
              }}>$23.95</span>
              <span style={{
                fontFamily: "Inter, sans-serif", fontSize: 11, fontWeight: 600,
                color: "#B85648", background: "rgba(217,119,87,0.12)",
                border: "1px solid rgba(217,119,87,0.30)",
                borderRadius: 999, padding: "3px 10px"
              }}>SAVE $15</span>
            </div>

            {/* CTA */}
            <a
              href={CHECKOUT_URL_EI}
              onClick={hide}
              className="cta-primary cta-pulse inline-flex items-center justify-center gap-2 no-underline w-full"
              style={{ height: 54, fontSize: 16, fontWeight: 700 }}>
              <span className="flex items-center gap-2">
                Start understanding my baby
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 12h14M12 5l7 7-7 7"/>
                </svg>
              </span>
            </a>

            {/* Micro-copy */}
            <div style={{
              display: "flex", flexWrap: "wrap", alignItems: "center",
              justifyContent: "center", gap: "4px 10px", marginTop: 10,
              fontFamily: "Inter, sans-serif", fontSize: 11, color: "#6B655B"
            }}>
              <span>Instant PDF</span>
              <span style={{ color: "#C8A24A" }}>·</span>
              <span>No subscription</span>
              <span style={{ color: "#C8A24A" }}>·</span>
              <span>Yours forever</span>
            </div>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes slideUpExit {
          from { transform: translateX(-50%) translateY(40px); opacity: 0; }
          to   { transform: translateX(-50%) translateY(0);    opacity: 1; }
        }
      `}</style>
    </>
  );
}

Object.assign(window, { DynamicTabTitle, ExitIntentOverlay });
