/* global React, Button, Icon, SiteNav, SiteFooter, AgentModal */
const { useEffect: useCSEffect } = React;

/* Re-use homepage tokens — kept in sync with Sections.jsx */
const CS_CANVAS_MAX = 1200;

const csEyebrow = {
  fontSize: 11,
  fontWeight: 600,
  letterSpacing: "0.16em",
  textTransform: "uppercase",
  color: "var(--bm-accent)",
  lineHeight: 1,
};

const csDisplayL = {
  fontFamily: "var(--bm-font-display)",
  fontSize: "clamp(36px, 4.4vw, 56px)",
  fontWeight: 700,
  letterSpacing: "-0.025em",
  lineHeight: 1.06,
  color: "var(--bm-text)",
  margin: 0,
};

const csDisplayM = {
  fontFamily: "var(--bm-font-display)",
  fontSize: "clamp(26px, 2.8vw, 36px)",
  fontWeight: 700,
  letterSpacing: "-0.02em",
  lineHeight: 1.12,
  color: "var(--bm-text)",
  margin: 0,
};

const csBodyL = { fontSize: 19, lineHeight: 1.55, color: "var(--bm-text-muted)", fontWeight: 400, margin: 0 };
const csBodyM = { fontSize: 16, lineHeight: 1.6,  color: "var(--bm-text-muted)", fontWeight: 400, margin: 0 };

/* Same signature glow used across the site */
function CSBottomLeftGlow() {
  return (
    <div aria-hidden style={{
      position: "absolute", inset: 0, pointerEvents: "none",
      background:
        "radial-gradient(ellipse 55% 50% at 0% 100%, rgba(0,24,125,0.72), rgba(0,11,69,0.28) 38%, rgba(0,3,34,0) 70%)",
    }} />
  );
}

/* Back link pinned below nav */
function BackLink() {
  return (
    <div style={{ maxWidth: CS_CANVAS_MAX, margin: "0 auto", padding: "24px 32px 0" }}>
      <a
        href="/case-studies"
        style={{
          display: "inline-flex",
          alignItems: "center",
          gap: 8,
          fontSize: 13,
          fontWeight: 500,
          color: "var(--bm-text-muted)",
          textDecoration: "none",
          transition: "color 120ms var(--bm-ease-standard)",
        }}
        onMouseEnter={(e) => { e.currentTarget.style.color = "var(--bm-accent)"; }}
        onMouseLeave={(e) => { e.currentTarget.style.color = "var(--bm-text-muted)"; }}
      >
        <Icon name="arrow-left" size={14} color="currentColor" />
        Back to Case Studies
      </a>
    </div>
  );
}

/* Hero: label + descriptor + big headline */
function CSHero({ label, descriptor, headline }) {
  return (
    <section data-bm-section="hero" style={{ position: "relative", padding: "64px 32px 64px", overflow: "hidden" }}>
      <CSBottomLeftGlow />
      <div style={{ position: "relative", maxWidth: CS_CANVAS_MAX, margin: "0 auto" }}>
        <div style={csEyebrow}>{label}</div>
        <p style={{ ...csBodyM, marginTop: 14, maxWidth: 720 }}>{descriptor}</p>
        <h1 style={{ ...csDisplayL, marginTop: 28, maxWidth: 1040 }}>{headline}</h1>
      </div>
    </section>
  );
}

/* Outcomes: hero stat callout + 5 bullets */
function CSOutcomes({ heroStat, outcomes }) {
  return (
    <section data-bm-section="mid" style={{ padding: "48px 32px" }}>
      <div style={{ maxWidth: CS_CANVAS_MAX, margin: "0 auto" }}>
        <div style={csEyebrow}>Outcomes</div>

        <div
          className="bm-neon-blue"
          style={{
            fontFamily: "var(--bm-font-display)",
            fontSize: "clamp(44px, 5.2vw, 72px)",
            fontWeight: 700,
            letterSpacing: "-0.03em",
            lineHeight: 1.02,
            marginTop: 20,
          }}
        >
          {heroStat}
        </div>

        <ul
          style={{
            marginTop: 40,
            padding: 0,
            listStyle: "none",
            display: "grid",
            gridTemplateColumns: "1fr",
            gap: 14,
            maxWidth: 900,
          }}
        >
          {outcomes.map((o, i) => (
            <li
              key={i}
              style={{
                display: "flex",
                alignItems: "flex-start",
                gap: 14,
                paddingBottom: 14,
                borderBottom: i < outcomes.length - 1 ? "1px solid var(--bm-hairline)" : "none",
              }}
            >
              <Icon name="check" size={18} color="var(--bm-accent)" style={{ marginTop: 3, flexShrink: 0 }} />
              <div style={{ fontSize: 16, lineHeight: 1.55 }}>
                <span style={{ color: "var(--bm-text)", fontWeight: 600 }}>{o.metric}</span>
                <span style={{ color: "var(--bm-text-muted)" }}> — {o.context}</span>
              </div>
            </li>
          ))}
        </ul>
      </div>
    </section>
  );
}

/* Challenge paragraph */
function CSChallenge({ text }) {
  return (
    <section data-bm-section="mid" style={{ padding: "48px 32px" }}>
      <div style={{ maxWidth: CS_CANVAS_MAX, margin: "0 auto" }}>
        <div style={csEyebrow}>The Challenge</div>
        <p style={{ ...csBodyL, marginTop: 18, maxWidth: 760 }}>{text}</p>
      </div>
    </section>
  );
}

/* Solution bullets */
function CSSolution({ items, tags }) {
  return (
    <section data-bm-section="mid" style={{ padding: "48px 32px 64px" }}>
      <div style={{ maxWidth: CS_CANVAS_MAX, margin: "0 auto" }}>
        <div style={csEyebrow}>What We Built</div>
        <ul
          style={{
            marginTop: 28,
            padding: 0,
            listStyle: "none",
            display: "flex",
            flexDirection: "column",
            gap: 14,
            maxWidth: 860,
          }}
        >
          {items.map((t, i) => (
            <li
              key={i}
              style={{
                display: "flex",
                gap: 14,
                fontSize: 16,
                lineHeight: 1.6,
                color: "var(--bm-text)",
              }}
            >
              <span
                style={{
                  flexShrink: 0,
                  width: 26,
                  height: 26,
                  borderRadius: 999,
                  background: "rgba(109,145,242,0.12)",
                  border: "1px solid rgba(109,145,242,0.28)",
                  color: "var(--bm-accent)",
                  fontSize: 12,
                  fontWeight: 600,
                  display: "inline-flex",
                  alignItems: "center",
                  justifyContent: "center",
                  marginTop: 2,
                }}
              >
                {i + 1}
              </span>
              <span>{t}</span>
            </li>
          ))}
        </ul>

        {tags && tags.length > 0 && (
          <div data-bm-tags style={{ marginTop: 36, display: "flex", flexWrap: "wrap", gap: 10 }}>
            {tags.map((t) => (
              <span
                key={t}
                style={{
                  display: "inline-flex",
                  alignItems: "center",
                  padding: "8px 14px",
                  borderRadius: 999,
                  fontSize: 12,
                  fontWeight: 500,
                  lineHeight: 1,
                  background: "rgba(109,145,242,0.15)",
                  color: "var(--bm-accent)",
                  border: "1px solid rgba(109,145,242,0.28)",
                }}
              >
                {t}
              </span>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}

/* Media embed — video if videoUrl, otherwise image if imageUrl. Skipped if neither. */
function CSMedia({ videoUrl, imageUrl, imageAlt, label = "See It Yourself" }) {
  if (!videoUrl && !imageUrl) return null;
  return (
    <section data-bm-section="mid" style={{ padding: "48px 32px" }}>
      <div style={{ maxWidth: CS_CANVAS_MAX, margin: "0 auto" }}>
        <div style={csEyebrow}>{label}</div>

        {videoUrl && (
          <div
            style={{
              position: "relative",
              marginTop: 28,
              maxWidth: 800,
              marginLeft: "auto",
              marginRight: "auto",
              aspectRatio: "16 / 9",
              borderRadius: 18,
              overflow: "hidden",
              border: "1px solid var(--bm-hairline-strong)",
              boxShadow: "0 40px 100px -40px rgba(109,145,242,0.35)",
              background: "#000",
            }}
          >
            <iframe
              src={videoUrl}
              title="Case study video"
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
              allowFullScreen
              style={{ position: "absolute", inset: 0, width: "100%", height: "100%", border: 0 }}
            />
          </div>
        )}

        {!videoUrl && imageUrl && (
          <div
            style={{
              position: "relative",
              marginTop: 28,
              maxWidth: 900,
              marginLeft: "auto",
              marginRight: "auto",
              borderRadius: 18,
              overflow: "hidden",
              border: "1px solid var(--bm-hairline-strong)",
              boxShadow: "0 40px 100px -40px rgba(109,145,242,0.35)",
              background: "#000318",
            }}
          >
            <img
              src={imageUrl}
              alt={imageAlt || ""}
              loading="lazy"
              style={{ display: "block", width: "100%", height: "auto" }}
            />
          </div>
        )}
      </div>
    </section>
  );
}

/* CTA — full-width dark block with calendar embed inline.
   Matches container height to the widget's reported height exactly (no
   cropping) so the Confirm button / form are always reachable on every
   state and on every viewport. */
function CSCta() {
  const IFRAME_ID = `${GHL_CAL_ID}_cs_${Date.now()}`;

  useCSEffect(() => {
    const apply = (reported) => {
      const ifr = document.getElementById(IFRAME_ID);
      const container = document.getElementById("cs-calendar");
      if (!ifr || !container) return;
      ifr.style.height = reported + "px";
      container.style.height = reported + "px";
    };

    const onMsg = (e) => {
      if (!e || !e.data) return;
      let targetHeight = null;
      if (typeof e.data === "string" && e.data.indexOf("[iFrameSizer]") === 0) {
        const parts = e.data.substring("[iFrameSizer]".length).split(":");
        if (parts.length >= 2) {
          const h = parseInt(parts[1], 10);
          if (!isNaN(h) && h > 0) targetHeight = h;
        }
      }
      let parsed = e.data;
      if (typeof parsed === "string") { try { parsed = JSON.parse(parsed); } catch (_) {} }
      if (Array.isArray(parsed) && parsed[0] === "highlevel.setHeight" && parsed[1]) {
        const h = parseInt(parsed[1].height, 10);
        if (!isNaN(h) && h > 0) targetHeight = h;
      }
      if (targetHeight) apply(targetHeight);
    };

    window.addEventListener("message", onMsg);
    return () => window.removeEventListener("message", onMsg);
  }, []);

  return (
    <section
      id="talk"
      data-bm-section="cta"
      style={{ padding: "96px 32px 128px", position: "relative", overflow: "hidden" }}
    >
      <CSBottomLeftGlow />
      <div style={{ position: "relative", maxWidth: CS_CANVAS_MAX, margin: "0 auto" }}>
        <div style={csEyebrow}>Every build is custom. See yours first.</div>
        <h2 style={{ ...csDisplayM, marginTop: 18, maxWidth: 820 }}>
          Let's find out if AI is the right move for your business.
        </h2>
        <p style={{ ...csBodyM, marginTop: 20, maxWidth: 680 }}>
          The first step is a free audit of your sales system. We'll tell you
          exactly what to build, in what order, and what ROI to expect.
          No pitch, no pressure.
        </p>

        <div data-bm-cta-row style={{ marginTop: 28, display: "flex", gap: 12, flexWrap: "wrap" }}>
          <Button variant="primary" icon="arrow-down"
            onClick={() => document.getElementById("cs-calendar")?.scrollIntoView({ behavior: "smooth", block: "start" })}>
            Book below
          </Button>
          <Button variant="secondary" icon="phone-call" onClick={openAgentModal}>
            Try the agent first
          </Button>
        </div>

        <div
          id="cs-calendar"
          data-bm-calendar
          style={{
            marginTop: 40,
            maxWidth: 1140,
            marginLeft: "auto",
            marginRight: "auto",
            background: "#ffffff",
            border: "none",
            borderRadius: 18,
            overflow: "hidden",
            position: "relative",
            boxShadow: "0 30px 80px -30px rgba(109,145,242,0.28)",
          }}
        >
          <iframe
            src={`${GHL_CAL_EMBED_URL}?notrack=true`}
            title="Discovery Call With Ruben (Founder & CEO)"
            style={{
              width: "100%",
              border: "none",
              display: "block",
              background: "#ffffff",
              WebkitOverflowScrolling: "touch",
            }}
            id={IFRAME_ID}
          />
        </div>
        <p
          style={{
            marginTop: 14,
            fontSize: 12,
            color: "var(--bm-text-muted)",
            textAlign: "center",
            letterSpacing: "0.08em",
            textTransform: "uppercase",
            fontWeight: 600,
          }}
        >
          Discovery call · 30 minutes · no pitch
        </p>
      </div>
    </section>
  );
}

/* Page wrapper: composes everything */
function CaseStudyPage({ data }) {
  return (
    <>
      <SiteNav />
      <BackLink />
      <main>
        <CSHero label={data.label} descriptor={data.descriptor} headline={data.headline} />
        <CSOutcomes heroStat={data.heroStat} outcomes={data.outcomes} />
        <CSChallenge text={data.challenge} />
        <CSSolution items={data.solution} tags={data.tags} />
        <CSMedia
          videoUrl={data.videoUrl}
          imageUrl={data.imageUrl}
          imageAlt={data.imageAlt}
          label={data.mediaLabel || (data.videoUrl ? "Hear It Yourself" : "See The Results")}
        />
        <CSCta />
      </main>
      <SiteFooter />
      <AgentModal />
    </>
  );
}

Object.assign(window, { CaseStudyPage });
