/* DOMINANCE — Page 4: Qualified (high score → instant Cal.com booking)
   Uses the official Cal.com embed.js (loader injected in index.html) so the
   booking widget renders inline with brand colors, dark theme, and pre-filled
   name/email from the form. Falls back to a mailto button if the link is
   missing or Cal fails to load. */

function QualifiedPage({ tweaks }) {
  // Cal link + identity stashed in sessionStorage at submit time. If a visitor
  // lands here directly (refresh / shared URL), nothing is stashed and we fall
  // back to the "contact me" plate.
  const [calLink, setCalLink] = React.useState("");
  const [prefill, setPrefill] = React.useState({ name: "", email: "" });

  React.useEffect(() => {
    try {
      setCalLink(sessionStorage.getItem("dominance_cal_link") || "");
      setPrefill({
        name: sessionStorage.getItem("dominance_lead_first_name") || "",
        email: sessionStorage.getItem("dominance_lead_email") || "",
      });
    } catch {
      setCalLink("");
    }
  }, []);

  // Cal.com embed.js wants the link as "<handle>/<event>" — strip the protocol
  // and host from whatever was stashed (full URL or already-relative path).
  const calPath = React.useMemo(() => {
    if (!calLink) return "";
    try {
      return new URL(calLink).pathname.replace(/^\//, "");
    } catch {
      return calLink.replace(/^https?:\/\/cal\.com\//, "").replace(/^\//, "");
    }
  }, [calLink]);

  // Initialize the inline embed once we have a path AND the Cal stub is ready.
  // Use column_view (compact side-by-side day picker + time slots) instead of
  // month_view — fits in one screen without making the visitor scroll.
  React.useEffect(() => {
    if (!calPath || typeof window === "undefined" || !window.Cal) return;

    const accent = tweaks?.accent || "#DC2626";
    const ns = "dominance";

    window.Cal("init", ns, { origin: "https://cal.com" });
    window.Cal.ns[ns]("inline", {
      elementOrSelector: "#dominance-cal-embed",
      calLink: calPath,
      config: {
        layout: "column_view",
        theme: "dark",
        ...(prefill.name ? { name: prefill.name } : {}),
        ...(prefill.email ? { email: prefill.email } : {}),
      },
    });
    window.Cal.ns[ns]("ui", {
      theme: "dark",
      cssVarsPerTheme: {
        light: { "cal-brand": accent },
        dark: { "cal-brand": accent },
      },
      layout: "column_view",
    });
  }, [calPath, prefill.name, prefill.email, tweaks?.accent]);

  // The custom cursor (cursor.js) can't track mouse movement inside the
  // Cal.com iframe, so it freezes at the iframe boundary while Cal shows its
  // own native cursor — visually awkward. On this page only, restore the
  // native OS cursor everywhere by removing the has-cursor class from <html>
  // and hiding the cursor dot/ring elements. Restored on unmount.
  React.useEffect(() => {
    if (typeof document === "undefined") return;
    const html = document.documentElement;
    const dot = document.querySelector(".cursor");
    const ring = document.querySelector(".cursor-ring");
    const hadHasCursor = html.classList.contains("has-cursor");

    html.classList.remove("has-cursor");
    if (dot) dot.style.display = "none";
    if (ring) ring.style.display = "none";

    return () => {
      if (hadHasCursor) html.classList.add("has-cursor");
      if (dot) dot.style.display = "";
      if (ring) ring.style.display = "";
    };
  }, []);

  return (
    <>
      <TopNav
        wordmark={true}
        status="Qualified — book your call"
        right={<span className="meta">QUALIFIED · BOOK NOW</span>}
      />
      <main className="confirm">
        <div className="confirm-card fade-in" style={{ maxWidth: 880 }}>
          <div className="confirm-mark fade-in">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 12.5l4.5 4.5L19 7.5" />
            </svg>
          </div>

          <img
            src="assets/dominance-wordmark-white.png"
            alt="DOMINANCE"
            className="confirm-wordmark fade-in-2"
          />

          <h1 className="display fade-in-2" style={{ fontSize: "clamp(36px, 5vw, 64px)" }}>
            You're a fit. Let's talk.
          </h1>

          <p className="lede fade-in-3" style={{ textAlign: "center", maxWidth: "56ch" }}>
            Based on your answers, I think we can help you. Pick a time that works
            below — 30 minutes, no pitch, just a walk-through of how this would look
            for your business specifically.
          </p>

          <div className="confirm-divider fade-in-3" />

          {calPath ? (
            <div
              id="dominance-cal-embed"
              className="fade-in-4"
              style={{ width: "100%", marginTop: 16, minHeight: 600 }}
            />
          ) : (
            <div className="fade-in-4" style={{ marginTop: 16, textAlign: "center" }}>
              <p className="confirm-small" style={{ marginBottom: 16 }}>
                The booking widget couldn't load. Reply to my confirmation email and
                I'll send you a link directly:
              </p>
              <a
                href="mailto:nik@dominance.business?subject=Booking my Revenue Growth Call"
                className="btn"
              >
                <span className="glint" />
                <span>Email Nik for a time</span>
                <span className="arrow">→</span>
              </a>
            </div>
          )}

          <p className="confirm-small fade-in-4" style={{ marginTop: 24 }}>
            Confirmation also goes to your inbox from{" "}
            <a href="mailto:nik@dominance.business">nik@dominance.business</a>.
            <br />Add me to your contacts so the calendar invite doesn't end up in spam.
          </p>

          <div className="confirm-sig fade-in-4" style={{ marginTop: 4 }}>— Nik</div>

          <div
            className="fade-in-4"
            style={{
              marginTop: 12,
              fontFamily: "var(--mono)",
              fontSize: 11,
              letterSpacing: "0.12em",
              textTransform: "uppercase",
              color: "var(--text-3)",
              display: "flex",
              gap: 14,
              alignItems: "center",
            }}
          >
            <span
              style={{
                width: 6,
                height: 6,
                background: "var(--accent)",
                borderRadius: "50%",
                boxShadow: "0 0 8px var(--accent)",
              }}
            />
            <span>Ref. {Math.random().toString(36).slice(2, 8).toUpperCase()}-{new Date().getFullYear()}</span>
            <span>·</span>
            <span>Qualified · Direct booking</span>
          </div>
        </div>
      </main>
      <Footer />
    </>
  );
}

window.QualifiedPage = QualifiedPage;
