// PowerCord Energy — Marketing Site UI Kit components.
// All components share the brand's tokens via colors_and_type.css.

const { useState } = React;

// Shared "Schedule a call" mailto link — used by every "Schedule a call"
// CTA across the entire marketing site (home + all v2 pages).
const SCHEDULE_CALL_MAILTO = "mailto:Sales@powercordenergy.com?subject=I%27m%20interested%20in%20PowerCord%20Energy.&body=I%20have%20reviewed%20your%20website%20and%20am%20interested%20in%20discussing%20PowerCord%20Energy%27s%20services%20for%20Texas%20multifamily.%20Please%20reply%20back%20to%20schedule%20a%20time%20for%20a%20brief%20introductory%20chat.";
window.SCHEDULE_CALL_MAILTO = SCHEDULE_CALL_MAILTO;

// ────────────────────────────────────────────────────────────
// Hosted explainer video URLs.
//
// Replace each placeholder with the public Vercel URL once the MP4s
// are uploaded. All video CTAs across the site reference these three
// constants — this is the only place they need to be updated.
//
//   VIDEO_INTRO_3MIN     → "PowerCord Energy Services Explainer.mp4"
//                          (used by every nav "Three-minute introduction"
//                          pill and the home-page footer CTA)
//   VIDEO_ELECTRICITY    → "PowerCord Electricity Revenue Explainer.mp4"
//                          (used by the "Three-minute explainer video"
//                          buttons in the Electricity Revenue sections)
//   VIDEO_TAX_RECAPTURE  → "PowerCord Energy Tax Recapture Explainer.mp4"
//                          (used by the "Three-minute explainer video"
//                          buttons in the Tax Recapture sections)
// ────────────────────────────────────────────────────────────
const VIDEO_INTRO_3MIN    = "/explainer.mp4";
const VIDEO_ELECTRICITY   = "/explainer-energy.mp4";
const VIDEO_TAX_RECAPTURE = "/explainer-tax.mp4";
window.VIDEO_INTRO_3MIN    = VIDEO_INTRO_3MIN;
window.VIDEO_ELECTRICITY   = VIDEO_ELECTRICITY;
window.VIDEO_TAX_RECAPTURE = VIDEO_TAX_RECAPTURE;

// ────────────────────────────────────────────────────────────
// Wordmark — live HTML rendering of Logo 2.0
// ────────────────────────────────────────────────────────────
function Wordmark({ onDark = false, size = 20 }) {
  const pcColor = onDark ? "#fff" : "#25476c";
  return (
    <span style={{
      fontFamily: "Inter, sans-serif",
      fontWeight: 800,
      fontSize: size,
      letterSpacing: "-0.3px",
      lineHeight: 1,
      whiteSpace: "nowrap",
    }}>
      <span style={{ color: pcColor }}>PowerCord</span>
      <span style={{ color: "#f9a727" }}>Energy</span>
    </span>
  );
}

// ────────────────────────────────────────────────────────────
// Nav
// ────────────────────────────────────────────────────────────
function Nav({ current }) {
  const items = [
    { id: "pmc",    label: "Property Managers", href: "/pmc" },
    { id: "owner",  label: "Property Owners",   href: "/owner-operator" },
    { id: "tax",    label: "Tax Recapture",     href: "/tax-recapture" },
    { id: "energy", label: "Energy Revenue",    href: "/energy-revenue.html" },
  ];
  return (
    <nav style={{
      background: "#1a3352",
      padding: "18px clamp(24px, 7vw, 112px)",
      display: "flex",
      alignItems: "center",
      justifyContent: "space-between",
      gap: 24,
    }}>
      <a href="/" style={{ textDecoration: "none" }}>
        <Wordmark onDark />
      </a>
      <div style={{ display: "flex", gap: 26, alignItems: "center" }}>
        {items.map(it => (
          <a key={it.id} href={it.href}
             style={{
               color: current === it.id ? "#fff" : "rgba(255,255,255,0.78)",
               fontSize: 14, fontWeight: 500, textDecoration: "none",
               transition: "color 220ms",
             }}>
            {it.label}
          </a>
        ))}
        <a href={VIDEO_INTRO_3MIN} rel="noopener" className="btn"
          onClick={function (e) {
            if (window.openVideoGate) {
              e.preventDefault();
              window.openVideoGate({
                videoSrc: VIDEO_INTRO_3MIN,
                videoTitle: "Three-minute introduction",
                videoId: "intro",
                endCta: { type: "audience-picker" }
              });
            }
          }}
          style={{
            padding: "10px 18px 10px 12px", fontSize: 13,
            display: "inline-flex", alignItems: "center", gap: 8,
          }}>
          <span aria-hidden="true" style={{
            width: 20, height: 20, borderRadius: "50%",
            background: "rgba(255,255,255,0.18)",
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            flexShrink: 0,
          }}>
            <svg width="8" height="9" viewBox="0 0 8 9" fill="none" aria-hidden="true">
              <path d="M0.5 0.5L7.5 4.5L0.5 8.5V0.5Z" fill="currentColor"/>
            </svg>
          </span>
          Three-minute introduction
        </a>
      </div>
    </nav>
  );
}

// ────────────────────────────────────────────────────────────
// Eyebrow + 48px rule (the brand signature card head)
// ────────────────────────────────────────────────────────────
function Eyebrow({ children, sm = false }) {
  return (
    <span style={{
      display: "inline-block",
      color: "#f14721",
      fontSize: sm ? 11 : 12,
      fontWeight: 700,
      letterSpacing: "2px",
      textTransform: "uppercase",
      marginBottom: 12,
    }}>{children}</span>
  );
}
function Rule() {
  return <hr style={{ width: 48, height: 3, background: "#f9a727", border: 0, margin: "12px 0 16px" }}/>;
}

// ────────────────────────────────────────────────────────────
// Trust badge — "X | Y | Z" three-token rhythm
// ────────────────────────────────────────────────────────────
function TrustBadge({ tokens, onDark = false }) {
  return (
    <p style={{
      color: onDark ? "rgba(255,255,255,0.72)" : "#5a6a7a",
      fontSize: 13, fontWeight: 600, margin: 0, maxWidth: 520,
    }}>
      {tokens.map((t, i) => (
        <React.Fragment key={i}>
          {t}
          {i < tokens.length - 1 && (
            <span style={{ color: "#f9a727", margin: "0 10px" }}>|</span>
          )}
        </React.Fragment>
      ))}
    </p>
  );
}

// ────────────────────────────────────────────────────────────
// Hero — two-column navy with white summary card
// ────────────────────────────────────────────────────────────
function Hero({ headline, sub, badge, card, image, imageAlt }) {
  return (
    <section style={{
      background: "#25476c",
      padding: "100px clamp(24px, 7vw, 112px) 80px",
    }}>
      <div style={{
        maxWidth: 1280, margin: "0 auto",
        display: "grid",
        gridTemplateColumns: "minmax(0, 1.2fr) minmax(0, 1fr)",
        gap: 48, alignItems: "center",
      }}>
        <div>
          <h1 style={{
            color: "#fff", fontWeight: 900,
            fontSize: "clamp(38px, 4.5vw, 58px)",
            letterSpacing: "-2px", lineHeight: 1.07, margin: "0 0 18px",
          }}>{headline}</h1>
          <p style={{
            color: "rgba(255,255,255,0.78)",
            fontSize: 18, lineHeight: 1.55, maxWidth: 540, margin: "0 0 24px",
          }}>{sub}</p>
          {badge && <TrustBadge tokens={badge} onDark/>}
        </div>
        {image ? (
          <div style={{
            borderRadius: 16,
            overflow: "hidden",
            aspectRatio: "4 / 3",
            boxShadow: "0 18px 40px rgba(0,0,0,0.28), 0 2px 8px rgba(0,0,0,0.18)",
            position: "relative",
          }}>
            <img src={image} alt={imageAlt || ""} style={{
              width: "100%", height: "100%", objectFit: "cover", display: "block",
            }}/>
          </div>
        ) : card}
      </div>
    </section>
  );
}

// ────────────────────────────────────────────────────────────
// HeroCard — white card to the right of the hero headline
// ────────────────────────────────────────────────────────────
function HeroCard({ eyebrow, title, body, ctaLabel, secondaryLabel, onCTA, ctas }) {
  // ctas: optional array of { label, onClick, variant: "primary" | "spark" }
  // Falls back to legacy ctaLabel/secondaryLabel/onCTA when ctas is not provided.
  return (
    <div style={{
      background: "#fff",
      borderRadius: 16,
      padding: "26px 28px",
      boxShadow: "0 2px 8px rgba(0,0,0,0.10), 0 1px 2px rgba(0,0,0,0.06)",
    }}>
      <Eyebrow>{eyebrow}</Eyebrow>
      <h3 style={{
        color: "#25476c", fontWeight: 800, fontSize: 22, margin: "0 0 6px",
        lineHeight: 1.25,
      }}>{title}</h3>
      <p style={{
        color: "#5a6a7a", fontSize: 15, lineHeight: 1.55, margin: "0 0 18px",
      }}>{body}</p>
      {ctas && ctas.length ? (
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          {ctas.map((c, i) => (
            <a key={i} href="#"
               className={"btn" + (c.variant === "ghost" ? " btn--ghost" : " btn--spark")}
               onClick={(e) => { e.preventDefault(); c.onClick && c.onClick(); }}
               style={{ width: "100%", boxSizing: "border-box", padding: "12px 22px", fontSize: 14,
                        display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8 }}>
              {c.label}
              {c.variant !== "ghost" && (
                <svg width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2.5"><path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3"/></svg>
              )}
            </a>
          ))}
        </div>
      ) : (
        <a href="#" className="btn btn--spark" onClick={(e) => { e.preventDefault(); onCTA && onCTA(); }}
           style={{ width: "100%", boxSizing: "border-box", padding: "12px 22px", fontSize: 14,
                    display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8 }}>
          {ctaLabel}
          <svg width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2.5"><path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3"/></svg>
        </a>
      )}
      {!ctas && secondaryLabel && (
        <div style={{
          marginTop: 14, paddingTop: 14, borderTop: "1px solid #dde4ec",
          fontSize: 13, color: "#5a6a7a",
        }}>
          Not sure yet? <a href="#" style={{ color: "#25476c", fontWeight: 600 }}
             onClick={(e) => e.preventDefault()}>{secondaryLabel} →</a>
        </div>
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Section frame — alternating bg, default 96px py, max-width
// ────────────────────────────────────────────────────────────
function Section({ children, bg = "#fff", style = {} }) {
  return (
    <section style={{
      background: bg, padding: "96px clamp(24px, 7vw, 112px)", ...style,
    }}>
      <div style={{ maxWidth: 1280, margin: "0 auto" }}>{children}</div>
    </section>
  );
}

// ────────────────────────────────────────────────────────────
// SectionHead — eyebrow + H2 statement
// ────────────────────────────────────────────────────────────
function SectionHead({ eyebrow, title, sub }) {
  return (
    <header style={{ marginBottom: 48, maxWidth: 720 }}>
      <Eyebrow>{eyebrow}</Eyebrow>
      <h2 style={{
        color: "#25476c", fontWeight: 900,
        fontSize: "clamp(28px, 3.5vw, 42px)",
        letterSpacing: "-0.8px", lineHeight: 1.15, margin: "0 0 16px",
      }}>{title}</h2>
      {sub && (
        <p style={{
          color: "#5a6a7a", fontSize: 18, lineHeight: 1.65,
          maxWidth: 680, margin: 0,
        }}>{sub}</p>
      )}
    </header>
  );
}

// ────────────────────────────────────────────────────────────
// ServiceCard — light card with Live Wire rule
// ────────────────────────────────────────────────────────────
function ServiceCard({ eyebrow, title, body, link, onClick, videoHref, videoLabel, videoId, endCta }) {
  return (
    <div style={{
      background: "#fff",
      border: "1px solid #dde4ec",
      borderRadius: 16,
      padding: "28px 30px",
      boxShadow: "0 2px 8px rgba(26,51,82,0.06), 0 1px 2px rgba(26,51,82,0.04)",
      transition: "box-shadow 220ms",
      cursor: onClick ? "pointer" : "default",
      display: "flex", flexDirection: "column",
      height: "100%",
    }}
    onClick={onClick}
    onMouseEnter={(e) => e.currentTarget.style.boxShadow = "0 4px 16px rgba(26,51,82,0.08), 0 2px 4px rgba(26,51,82,0.06)"}
    onMouseLeave={(e) => e.currentTarget.style.boxShadow = "0 2px 8px rgba(26,51,82,0.06), 0 1px 2px rgba(26,51,82,0.04)"}>
      <Eyebrow>{eyebrow}</Eyebrow>
      <h3 style={{
        color: "#25476c", fontWeight: 800, fontSize: 22, margin: 0,
        lineHeight: 1.2,
      }}>{title}</h3>
      <Rule/>
      <p style={{ color: "#5a6a7a", fontSize: 15, lineHeight: 1.6, margin: "0 0 18px", flex: 1 }}>{body}</p>
      <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 14 }}>
        <a href="#" onClick={(e) => { e.preventDefault(); onClick && onClick(); }}
           style={{ color: "#25476c", fontSize: 14, fontWeight: 600,
                    textDecoration: "none", borderBottom: "1px solid #dde4ec", paddingBottom: 1 }}>
          {link} →
        </a>
        {videoHref && (
          <a href={videoHref} rel="noopener" className="btn"
             style={{
               padding: "10px 16px 10px 10px",
               fontSize: 13,
               display: "inline-flex", alignItems: "center", gap: 8,
             }}
             onClick={(e) => {
               e.stopPropagation();
               if (window.openVideoGate) {
                 e.preventDefault();
                 window.openVideoGate({
                   videoSrc: videoHref,
                   videoTitle: title,
                   videoId: videoId,
                   endCta: endCta
                 });
               }
             }}>
            <span aria-hidden="true" style={{
              width: 18, height: 18, borderRadius: "50%",
              background: "rgba(255,255,255,0.18)",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              flexShrink: 0,
            }}>
              <svg width="7" height="8" viewBox="0 0 8 9" fill="none" aria-hidden="true">
                <path d="M0.5 0.5L7.5 4.5L0.5 8.5V0.5Z" fill="currentColor"/>
              </svg>
            </span>
            {videoLabel || "Three-minute explainer video"}
          </a>
        )}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// FeatureStack — numbered, no bullets
// ────────────────────────────────────────────────────────────
function FeatureStack({ items }) {
  return (
    <div style={{ maxWidth: 680 }}>
      {items.map((it, i) => (
        <div key={i} style={{
          display: "grid",
          gridTemplateColumns: "44px 1fr",
          gap: 18,
          padding: "20px 0",
          borderBottom: i < items.length - 1 ? "1px solid #dde4ec" : 0,
          alignItems: "start",
        }}>
          <span style={{
            fontFamily: "Inter, sans-serif", fontWeight: 900,
            fontSize: 22, color: "#f9a727", letterSpacing: "-0.5px",
          }}>{String(i + 1).padStart(2, "0")}</span>
          <div>
            <h4 style={{
              fontWeight: 800, fontSize: 18, color: "#25476c",
              margin: "0 0 6px", lineHeight: 1.3,
            }}>{it.title}</h4>
            <p style={{ fontSize: 15, color: "#5a6a7a", margin: 0, lineHeight: 1.6 }}>{it.body}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// Callout — Warm Current, brand category framing
// ────────────────────────────────────────────────────────────
function Callout({ children }) {
  return (
    <div style={{
      background: "#ffdda6", borderRadius: 12,
      padding: "22px 26px", color: "#25476c",
      fontSize: 18, fontWeight: 600, lineHeight: 1.5,
      maxWidth: 720,
      display: "inline-block",
    }}>{children}</div>
  );
}

// ────────────────────────────────────────────────────────────
// DarkCallout — Conductor Dark panel
// ────────────────────────────────────────────────────────────
function DarkCallout({ eyebrow, title, body, standalone }) {
  return (
    <div style={{
      background: standalone ? "transparent" : "#1a3352",
      borderRadius: standalone ? 0 : 16,
      padding: standalone ? 0 : "44px 48px",
      color: "#fff",
      maxWidth: 760,
    }}>
      <span style={{
        color: "#f14721", fontSize: 11, fontWeight: 700, letterSpacing: "2px",
        textTransform: "uppercase", display: "block", marginBottom: 12,
      }}>{eyebrow}</span>
      <h3 style={{
        color: "#fff", fontWeight: 800,
        fontSize: standalone ? 32 : 26,
        margin: "0 0 14px", lineHeight: 1.2, letterSpacing: standalone ? "-0.4px" : 0,
      }}>{title}</h3>
      {Array.isArray(body) ? (
        body.map((p, i) => (
          <p key={i} style={{
            color: "rgba(255,255,255,0.78)", fontSize: 16, lineHeight: 1.7,
            margin: i === 0 ? 0 : "16px 0 0",
          }}>{p}</p>
        ))
      ) : (
        <p style={{ color: "rgba(255,255,255,0.78)", fontSize: 16, lineHeight: 1.7, margin: 0 }}>{body}</p>
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// FooterCTA — full-width navy with amber + white
// ────────────────────────────────────────────────────────────
function FooterCTA({ headline, sub, onCTA }) {
  return (
    <section style={{
      background: "var(--clean-slate)",
      padding: "100px clamp(24px, 7vw, 112px)",
      textAlign: "center",
    }}>
      <div style={{ maxWidth: 720, margin: "0 auto" }}>
        <h2 style={{
          color: "#25476c", fontWeight: 900,
          fontSize: "clamp(28px, 3.5vw, 42px)",
          letterSpacing: "-0.8px", margin: "0 0 16px", lineHeight: 1.15,
        }}>{headline}</h2>
        <p style={{
          color: "#5a6a7a", fontSize: 18,
          lineHeight: 1.55, margin: "0 0 28px",
        }}>{sub}</p>
        <div style={{ display: "flex", gap: 12, justifyContent: "center", flexWrap: "wrap" }}>
          <a href={SCHEDULE_CALL_MAILTO} className="btn btn--spark"
             style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
            Schedule a call
            <svg width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2.5"><path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3"/></svg>
          </a>
          <a href={VIDEO_INTRO_3MIN} rel="noopener" className="btn"
             onClick={function (e) {
               if (window.openVideoGate) {
                 e.preventDefault();
                 window.openVideoGate({
                   videoSrc: VIDEO_INTRO_3MIN,
                   videoTitle: "Three-minute introduction",
                   videoId: "intro",
                   endCta: { type: "audience-picker" }
                 });
               }
             }}
             style={{
               padding: "14px 22px 14px 14px",
               fontSize: "var(--fs-button)",
               display: "inline-flex", alignItems: "center", gap: 10,
             }}>
            <span aria-hidden="true" style={{
              width: 22, height: 22, borderRadius: "50%",
              background: "rgba(255,255,255,0.18)",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              flexShrink: 0,
            }}>
              <svg width="9" height="10" viewBox="0 0 8 9" fill="none" aria-hidden="true">
                <path d="M0.5 0.5L7.5 4.5L0.5 8.5V0.5Z" fill="currentColor"/>
              </svg>
            </span>
            Three-minute explainer video
          </a>
        </div>
      </div>
    </section>
  );
}

// ────────────────────────────────────────────────────────────
// Footer — copyright + legal
// ────────────────────────────────────────────────────────────
function Footer() {
  return (
    <footer style={{
      background: "#1a3352",
      padding: "32px clamp(24px, 7vw, 112px)",
      display: "flex",
      alignItems: "center",
      justifyContent: "space-between",
      borderTop: "1px solid rgba(255,255,255,0.08)",
      flexWrap: "wrap", gap: 16,
    }}>
      <Wordmark onDark size={16}/>
      <div style={{ display: "flex", gap: 22, alignItems: "center" }}>
        <a href="#" style={{ color: "rgba(255,255,255,0.6)", fontSize: 13, textDecoration: "none" }} onClick={(e) => e.preventDefault()}>Privacy</a>
        <a href="#" style={{ color: "rgba(255,255,255,0.6)", fontSize: 13, textDecoration: "none" }} onClick={(e) => e.preventDefault()}>Contact</a>
        <span style={{ color: "rgba(255,255,255,0.4)", fontSize: 13 }}>© 2026 PowerCord Energy</span>
      </div>
    </footer>
  );
}

// ────────────────────────────────────────────────────────────
// AudienceSwitch — inline soft-charge link above hero
// ────────────────────────────────────────────────────────────
function AudienceSwitch({ otherLabel, onSwitch }) {
  return (
    <div style={{ background: "#1a3352", padding: "16px clamp(24px, 7vw, 112px)", borderTop: "1px solid rgba(255,255,255,0.06)" }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", display: "flex", alignItems: "center", gap: 10 }}>
        <span style={{ color: "rgba(255,255,255,0.6)", fontSize: 13 }}>Looking for {otherLabel}?</span>
        <a href="#" onClick={(e) => { e.preventDefault(); onSwitch(); }}
           style={{ color: "#f9a727", fontSize: 13, fontWeight: 600, textDecoration: "none" }}>
          Switch to that path →
        </a>
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// VideoGateModal — gated overlay for every explainer video CTA.
//
// Visitors fill a contact-capture form, then watch the video, then see an
// end-of-video CTA pointing to the right next step (calculator, schedule
// a call, audience picker, etc).
//
// Triggered from anywhere on any page via:
//   window.openVideoGate({
//     videoSrc: "/explainer-tax.mp4",
//     videoTitle: "Tax Recapture explainer",
//     videoId: "tax-recapture",   // intro | electricity | tax-recapture
//     endCta: { label: "Calculate Your Recovery", href: "/tax-recapture" },
//   });
//
// Returning visitors who have already submitted skip the form (localStorage
// flag). Submissions land in HubSpot via /api/video-gate.
// ────────────────────────────────────────────────────────────
function VideoGateModal({ open, videoSrc, videoTitle, videoId, endCta, onClose }) {
  const [step, setStep] = useState("form"); // "form" | "playing" | "ended"
  const [form, setForm] = useState({
    firstname: "", lastname: "", email: "", phone: "",
    company: "", property: "", units_managed: "",
  });
  const [status, setStatus] = useState("idle"); // idle | submitting | error
  const [errMsg, setErrMsg] = useState("");
  const videoRef = React.useRef(null);

  React.useEffect(() => {
    if (!open) return;
    var passed = false;
    try {
      passed = (typeof localStorage !== "undefined")
        && localStorage.getItem("pce_video_gate_passed") === "true";
    } catch (e) { passed = false; }
    setStep(passed ? "playing" : "form");
    setStatus("idle");
    setErrMsg("");
    var onKey = function (e) { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", onKey);
    var prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return function () {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = prevOverflow;
    };
  }, [open, onClose]);

  React.useEffect(() => {
    if (step === "playing" && videoRef.current) {
      videoRef.current.play().catch(function () { /* autoplay blocked — user can click play */ });
    }
  }, [step]);

  if (!open) return null;

  var updateForm = function (k) { return function (e) {
    setForm(Object.assign({}, form, { [k]: e.target.value }));
  }; };

  var handleSubmit = async function (e) {
    e.preventDefault();
    if (status === "submitting") return;
    setStatus("submitting");
    setErrMsg("");
    try {
      var payload = Object.assign({}, form, {
        video_id: videoId || "",
        property_name: form.property
      });
      var res = await fetch("/api/video-gate", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
      });
      var data = {};
      try { data = await res.json(); } catch (e) { data = {}; }
      if (!res.ok) {
        throw new Error(data.error || ("Request failed (" + res.status + ")"));
      }
      try { localStorage.setItem("pce_video_gate_passed", "true"); } catch (e) {}
      setStatus("idle");
      setStep("playing");
    } catch (err) {
      console.error("video-gate submit", err);
      setStatus("error");
      setErrMsg((err && err.message) || "Something went wrong. Please try again or email info@powercordenergy.com.");
    }
  };

  var handleVideoEnded = function () { setStep("ended"); };

  var fld = {
    width: "100%", boxSizing: "border-box",
    border: "1px solid #dde4ec", borderRadius: 4, padding: "0 14px", height: 44,
    fontFamily: "Inter, sans-serif", fontSize: 15, color: "#25476c", outline: "none",
    background: "#fff",
  };
  var lbl = { fontSize: 12, fontWeight: 600, color: "#5a6a7a",
              letterSpacing: "0.3px", marginBottom: 6, display: "block" };
  var row = { display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 };

  // Renders the end CTA. If endCta has an `onClick`, run it; else navigate to href.
  var renderEndCta = function () {
    if (!endCta) {
      return (
        <a href={SCHEDULE_CALL_MAILTO} className="btn btn--spark"
           style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
          Schedule a call
          <svg width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2.5"><path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3"/></svg>
        </a>
      );
    }
    // Two-button "Pick your path" splash for the intro video
    if (endCta.type === "audience-picker") {
      return (
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
          <a href="/pmc" className="btn"
             style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8, padding: "12px 22px" }}>
            I manage properties for clients
            <svg width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2.5"><path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3"/></svg>
          </a>
          <a href="/owner-operator" className="btn btn--spark"
             style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8, padding: "12px 22px" }}>
            I own my own properties
            <svg width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2.5"><path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3"/></svg>
          </a>
        </div>
      );
    }
    // Standard single-button CTA
    return (
      <a href={endCta.href || "#"}
         onClick={endCta.onClick ? function (e) { e.preventDefault(); onClose(); endCta.onClick(); } : undefined}
         className="btn btn--spark"
         style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
        {endCta.label || "Continue"}
        <svg width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2.5"><path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3"/></svg>
      </a>
    );
  };

  return (
    <div role="dialog" aria-modal="true" aria-labelledby="video-gate-title"
         onClick={function (e) { if (e.target === e.currentTarget) onClose(); }}
         style={{
           position: "fixed", inset: 0, background: "rgba(0,0,0,0.78)",
           display: "flex", alignItems: "center", justifyContent: "center",
           padding: 20, zIndex: 2000,
         }}>
      <div style={{
        background: "#fff", borderRadius: 12,
        width: "100%", maxWidth: step === "playing" ? 880 : 560,
        padding: step === "playing" ? "20px 20px 16px" : "32px 32px 28px",
        position: "relative", maxHeight: "92vh", overflowY: "auto",
        boxShadow: "0 40px 120px rgba(0,0,0,0.5)",
      }}>
        <button onClick={onClose} aria-label="Close"
                style={{
                  position: "absolute", top: 10, right: 14, background: "none", border: 0,
                  fontSize: 24, lineHeight: 1, color: "#94a8bc", cursor: "pointer", padding: 6,
                  zIndex: 1,
                }}>×</button>

        {step === "form" && (
          <>
            <span style={{ color: "#f14721", fontSize: 11, fontWeight: 700,
                           letterSpacing: "2px", textTransform: "uppercase",
                           display: "block", marginBottom: 10 }}>{videoTitle || "Explainer video"}</span>
            <h3 id="video-gate-title" style={{ color: "#25476c", fontWeight: 800, fontSize: 22,
                                                margin: "0 0 8px", lineHeight: 1.25 }}>
              Watch the explainer.
            </h3>
            <p style={{ color: "#5a6a7a", fontSize: 14, lineHeight: 1.55, margin: "0 0 22px" }}>
              Tell us a little about you and the video plays right after.
            </p>
            <form onSubmit={handleSubmit} style={{ display: "grid", gap: 14 }}>
              <div style={row}>
                <div>
                  <label style={lbl}>First name</label>
                  <input required value={form.firstname} onChange={updateForm("firstname")} style={fld} autoComplete="given-name"/>
                </div>
                <div>
                  <label style={lbl}>Last name</label>
                  <input required value={form.lastname} onChange={updateForm("lastname")} style={fld} autoComplete="family-name"/>
                </div>
              </div>
              <div>
                <label style={lbl}>Work email</label>
                <input required type="email" value={form.email} onChange={updateForm("email")} style={fld} autoComplete="email"/>
              </div>
              <div>
                <label style={lbl}>Phone <span style={{ color: "#94a8bc", fontWeight: 400 }}>(optional)</span></label>
                <input type="tel" value={form.phone} onChange={updateForm("phone")} style={fld} autoComplete="tel"/>
              </div>
              <div>
                <label style={lbl}>Company / Owning entity</label>
                <input required value={form.company} onChange={updateForm("company")} style={fld} autoComplete="organization"/>
              </div>
              <div>
                <label style={lbl}>Property name</label>
                <input required value={form.property} onChange={updateForm("property")} style={fld}/>
              </div>
              <div>
                <label style={lbl}>Total units under management</label>
                <select required value={form.units_managed} onChange={updateForm("units_managed")} style={fld}>
                  <option value="">Select a range...</option>
                  <option value="0 units">0 units</option>
                  <option value="1-50 units">1-50 units</option>
                  <option value="51-200 units">51-200 units</option>
                  <option value="201-500 units">201-500 units</option>
                  <option value="501-1000 units">501-1000 units</option>
                  <option value="1000+ units">1000+ units</option>
                </select>
              </div>
              {status === "error" && (
                <div style={{ background: "#fdecea", color: "#8a1f17", borderRadius: 6,
                              padding: "10px 14px", fontSize: 13, lineHeight: 1.5 }}>
                  {errMsg}
                </div>
              )}
              <button type="submit" disabled={status === "submitting"} className="btn btn--spark"
                      style={{
                        marginTop: 4, border: 0, cursor: status === "submitting" ? "wait" : "pointer",
                        opacity: status === "submitting" ? 0.7 : 1,
                        display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
                        padding: "12px 22px", fontSize: 14, width: "100%", boxSizing: "border-box",
                      }}>
                {status === "submitting" ? "Loading the video..." : "Watch the video"}
                {status !== "submitting" && (
                  <svg width="14" height="14" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth="2.5"><path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3"/></svg>
                )}
              </button>
              <p style={{ fontSize: 12, color: "#94a8bc", lineHeight: 1.5, margin: "4px 0 0", textAlign: "center" }}>
                We use your information only to follow up about PowerCord Energy services.
              </p>
            </form>
          </>
        )}

        {step === "playing" && (
          <>
            <h3 id="video-gate-title" style={{ color: "#25476c", fontWeight: 800, fontSize: 18,
                                                margin: "0 0 12px", lineHeight: 1.25 }}>
              {videoTitle || "Explainer video"}
            </h3>
            <video
              ref={videoRef}
              src={videoSrc}
              controls
              autoPlay
              playsInline
              onEnded={handleVideoEnded}
              style={{
                width: "100%", height: "auto", maxHeight: "70vh",
                borderRadius: 6, background: "#000", display: "block",
              }}
            />
          </>
        )}

        {step === "ended" && (
          <>
            <span style={{ color: "#f14721", fontSize: 11, fontWeight: 700,
                           letterSpacing: "2px", textTransform: "uppercase",
                           display: "block", marginBottom: 10 }}>Next step</span>
            <h3 id="video-gate-title" style={{ color: "#25476c", fontWeight: 800, fontSize: 22,
                                                margin: "0 0 12px", lineHeight: 1.25 }}>
              Ready to see your numbers?
            </h3>
            <p style={{ color: "#5a6a7a", fontSize: 15, lineHeight: 1.55, margin: "0 0 22px" }}>
              Pick up where the video left off.
            </p>
            <div style={{ marginBottom: 16 }}>{renderEndCta()}</div>
            <button onClick={() => setStep("playing")}
                    style={{
                      background: "none", border: 0, color: "#5a6a7a",
                      fontSize: 13, fontWeight: 600, cursor: "pointer",
                      padding: 0, textDecoration: "underline",
                    }}>
              Watch again
            </button>
          </>
        )}
      </div>
    </div>
  );
}

// ────────────────────────────────────────────────────────────
// VideoGateRoot — singleton mount that wires window.openVideoGate
// ────────────────────────────────────────────────────────────
function VideoGateRoot() {
  const [state, setState] = useState({ open: false });
  React.useEffect(function () {
    window.openVideoGate = function (opts) {
      setState(Object.assign({}, opts, { open: true }));
    };
    return function () { try { delete window.openVideoGate; } catch (e) { window.openVideoGate = undefined; } };
  }, []);
  return (
    <VideoGateModal
      open={!!state.open}
      videoSrc={state.videoSrc}
      videoTitle={state.videoTitle}
      videoId={state.videoId}
      endCta={state.endCta}
      onClose={function () { setState({ open: false }); }}
    />
  );
}

// Auto-mount the gate root once per page load.
(function mountVideoGateRoot() {
  if (typeof document === "undefined") return;
  if (window.__pceVideoGateMounted) return;
  var div = document.createElement("div");
  div.id = "pce-video-gate-root";
  document.body.appendChild(div);
  ReactDOM.createRoot(div).render(<VideoGateRoot/>);
  window.__pceVideoGateMounted = true;
})();

Object.assign(window, {
  Wordmark, Nav, Eyebrow, Rule, TrustBadge,
  Hero, HeroCard, Section, SectionHead,
  ServiceCard, FeatureStack, Callout, DarkCallout,
  FooterCTA, Footer, AudienceSwitch,
  VideoGateModal, VideoGateRoot,
});
