/* Workfloor — Demo walkthrough popup (DemoPopup)
   Lead-gate behind site CTAs. Captures info, then routes to a Cal.com booking.
   Spec-driven: copy is locked, fields ordered, phone auto-formats.
   ============================================================ */

const { useState: usePopState, useEffect: usePopEff, useRef: usePopRef } = React;

const DISMISS_KEY = "wf-demo-popup-dismissed-v1";

/* 2×2 brand mark per spec */
const DemoMark = () =>
<div style={{ display: "grid", gridTemplateColumns: "14px 14px", gridTemplateRows: "14px 14px", gap: 4, width: 32, height: 32 }} aria-hidden>
    <span style={{ background: "#D89968", borderRadius: 3 }} />
    <span style={{ background: "#F5DDC2", borderRadius: 3 }} />
    <span style={{ borderRadius: 3, background: "rgb(232, 147, 74)", opacity: "0.8" }} />
    <span style={{ background: "#F5DDC2", borderRadius: 3 }} />
  </div>;


/* Phone auto-format: 5551234567 -> (555) 123-4567 */
const formatPhone = (raw) => {
  const d = (raw || "").replace(/\D/g, "").slice(0, 10);
  if (d.length === 0) return "";
  if (d.length < 4) return `(${d}`;
  if (d.length < 7) return `(${d.slice(0, 3)}) ${d.slice(3)}`;
  return `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6)}`;
};

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

/* ---------- Sub-components ---------- */

const Check = () =>
<svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden style={{ flexShrink: 0 }}>
    <path d="M2.5 7.5L5.5 10.5L11.5 4" stroke="#E8934A" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
  </svg>;


const FieldLabel = ({ children, required }) =>
<label style={{ display: "block", fontSize: 13, fontWeight: 700, color: "#F5F3EE", marginBottom: 6, fontFamily: "var(--font-display)", letterSpacing: "-0.005em" }}>
    {children}{required && <span style={{ color: "#E8934A" }}> *</span>}
  </label>;


const baseInputStyle = (hasError) => ({
  width: "100%",
  padding: "12px 14px",
  background: "#0a121d",
  border: `1px solid ${hasError ? "#E85A4A" : "rgba(255,255,255,0.1)"}`,
  borderRadius: 8,
  color: "#F5F3EE",
  fontSize: 14,
  fontFamily: "var(--font-body)",
  outline: "none",
  boxSizing: "border-box",
  transition: "border-color 0.18s"
});

const focusOn = (e) => {if (!e.target.dataset.error) e.target.style.borderColor = "#E8934A";};
const focusOff = (e) => {if (!e.target.dataset.error) e.target.style.borderColor = "rgba(255,255,255,0.1)";};

/* ---------- Main popup ---------- */

const AuditPopup = ({ trigger = "timed", delaySec = 18, force = 0, open: openProp = false, onClose }) => {
  const [open, setOpen] = usePopState(openProp);
  const [submitted, setSubmitted] = usePopState(false);
  const [form, setForm] = usePopState({ owner: "", business: "", email: "", phone: "", slowdown: "", calls: "" });
  const [errors, setErrors] = usePopState({});
  const firedRef = usePopRef(false);

  // External force trigger (changes value -> open)
  usePopEff(() => {if (force) {setOpen(true);firedRef.current = true;}}, [force]);

  // Mark as 'seen' for this user the first time the popup is shown, so it
  // never appears again — even if they don't close it. Guarantees once-per-user.
  const markSeen = () => { try { localStorage.setItem(DISMISS_KEY, "1"); } catch (e) {} };
  const fire = () => { setOpen(true); firedRef.current = true; markSeen(); };

  // Auto trigger
  usePopEff(() => {
    if (force) return;
    if (trigger === "off") return;
    if (localStorage.getItem(DISMISS_KEY) === "1") return;

    let timer;let off;
    if (trigger === "timed") {
      timer = setTimeout(() => {if (!firedRef.current) {fire();}}, delaySec * 1000);
    } else if (trigger === "exit") {
      const h = (e) => {if (!firedRef.current && e.clientY < 8) {fire();}};
      document.addEventListener("mouseout", h);
      off = () => document.removeEventListener("mouseout", h);
    } else if (trigger === "scroll") {
      const h = () => {
        if (firedRef.current) return;
        const pct = window.scrollY / (document.body.scrollHeight - window.innerHeight);
        if (pct > 0.45) {fire();}
      };
      window.addEventListener("scroll", h, { passive: true });
      off = () => window.removeEventListener("scroll", h);
    }

    return () => {if (timer) clearTimeout(timer);if (off) off();};
  }, [trigger, delaySec, force]);

  // Escape & body scroll lock
  usePopEff(() => {
    if (!open) return;
    const onKey = (e) => {if (e.key === "Escape") close();};
    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {document.removeEventListener("keydown", onKey);document.body.style.overflow = "";};
  }, [open]);

  const close = () => {
    setOpen(false);
    if (!force) localStorage.setItem(DISMISS_KEY, "1");
    onClose && onClose();
  };

  const update = (k, v) => {
    setForm((f) => ({ ...f, [k]: v }));
    if (errors[k]) setErrors((er) => ({ ...er, [k]: null }));
  };

  const submit = (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.owner.trim()) errs.owner = "Required.";
    if (!form.business.trim()) errs.business = "Required.";
    if (!form.email.trim()) errs.email = "Required.";else
    if (!EMAIL_RE.test(form.email.trim())) errs.email = "Enter a valid email.";
    if (!form.phone.trim()) errs.phone = "Required.";else
    if (form.phone.replace(/\D/g, "").length < 10) errs.phone = "Enter a 10-digit phone.";
    setErrors(errs);
    if (Object.keys(errs).length === 0) setSubmitted(true);
  };

  if (!open) return null;

  return (
    <div
      className="wf-popup-overlay"
      onClick={(e) => {if (e.target === e.currentTarget) close();}}
      style={{
        position: "fixed", inset: 0, zIndex: 50,
        background: "rgba(0,0,0,0.85)",
        display: "flex", alignItems: "center", justifyContent: "center",
        padding: 40,
        animation: "wf-popup-fade 0.28s ease both"
      }}>
      
      <div
        className="wf-demo-popup"
        role="dialog"
        aria-modal="true"
        aria-labelledby="wf-demo-popup-title"
        style={{
          position: "relative",
          width: "100%",
          maxWidth: 1024,
          maxHeight: "calc(100vh - 80px)",
          overflow: "auto",
          borderRadius: 12,
          boxShadow: "0 40px 120px rgba(0,0,0,0.6), 0 0 0 1px rgba(255,255,255,0.05)",
          animation: "wf-popup-rise 0.4s cubic-bezier(0.2, 0.8, 0.2, 1) both",
          display: "grid",
          gridTemplateColumns: "1fr 1fr",
          background: "#080f18"
        }}>
        
        {/* ---------------- LEFT COLUMN — value prop (#080f18) ---------------- */}
        <div style={{
          background: "#080f18",
          padding: "44px 44px 44px",
          display: "flex",
          flexDirection: "column",
          gap: 28,
          position: "relative",
          overflow: "hidden"
        }}>
          {/* Subtle amber glow */}
          <div style={{ position: "absolute", width: 320, height: 320, borderRadius: "50%", background: "rgba(232,147,74,0.07)", filter: "blur(60px)", bottom: -120, left: -80, pointerEvents: "none" }} aria-hidden />

          {/* Brand mark */}
          <div style={{ display: "flex", alignItems: "center", gap: 12, position: "relative" }}>
            <DemoMark />
            <span style={{ fontSize: 18, fontWeight: 700, color: "#F5F3EE", fontFamily: "var(--font-display)", letterSpacing: "-0.01em" }}>Workfloor</span>
          </div>

          {/* Eyebrow */}
          <div style={{
            fontSize: 11,
            color: "#E8934A",
            fontWeight: 700,
            letterSpacing: "1.4px",
            textTransform: "uppercase",
            fontFamily: "var(--font-display)",
            position: "relative"
          }}>SEE HOW WE'LL DRIVE YOU MORE REVENUE· 20 MIN

          </div>

          {/* Headline */}
          <h2 id="wf-demo-popup-title" style={{
            fontSize: "clamp(28px, 3vw, 40px)",
            fontWeight: 700,

            lineHeight: 1.2,
            letterSpacing: "-0.02em",
            margin: 0,
            fontFamily: "var(--font-display)",
            position: "relative", color: "rgb(255, 255, 255)"
          }}>
            <br />
            <em style={{ color: "#E8934A", fontStyle: "italic", fontWeight: 700, fontSize: "30px" }}>78% of homeowners book whoever calls back first.</em><br />
            <span style={{ color: "#F5F3EE", fontStyle: "italic", fontWeight: 700, margin: "30px 0px 0px", fontSize: "6px" }}>How long does your response take?</span>
          </h2>

          {/* Sub copy */}
          <p style={{ fontSize: 15,
            color: "#9AAABB",
            lineHeight: 1.6,
            margin: 0,
            position: "relative",
            fontFamily: "var(--font-body)"
          }}>Most owners are off by more than they think. Book 20 minutes — we'll walk you through the system live and tell you straight how we'll save and make you more money

          </p>

          {/* Trust checklist */}
          <div style={{ display: "flex", flexDirection: "column", gap: 12, position: "relative", marginTop: "auto" }}>
            {[
            "20-minute live demo",
            "Serving HVAC-only",
            "We'll show you exactly how we will save the money you're losing",
            "No follow-up unless you ask"].
            map((line) =>
            <div key={line} style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 14, color: "#F5F3EE", fontFamily: "var(--font-display)", fontWeight: 500, letterSpacing: "-0.005em" }}>
                <Check />
                <span>{line}</span>
              </div>
            )}
          </div>
        </div>

        {/* ---------------- RIGHT COLUMN — form (#03070d) ---------------- */}
        <div style={{
          background: "#03070d",
          padding: "44px 44px 44px",
          position: "relative",
          display: "flex",
          flexDirection: "column"
        }}>
          {/* Close button */}
          <button
            type="button"
            onClick={close}
            aria-label="Close"
            style={{
              position: "absolute", top: 16, right: 18,
              width: 30, height: 30, borderRadius: 6,
              background: "transparent", border: "none",
              color: "#6A7D8E", fontSize: 20, lineHeight: 1, cursor: "pointer",
              display: "flex", alignItems: "center", justifyContent: "center",
              transition: "color 0.18s"
            }}
            onMouseEnter={(e) => {e.currentTarget.style.color = "#F5F3EE";}}
            onMouseLeave={(e) => {e.currentTarget.style.color = "#6A7D8E";}}>
            
            ✕
          </button>

          {submitted ?
          <div>
              <div style={{
              fontSize: 11, color: "#E8934A", fontWeight: 700, letterSpacing: "1.4px",
              textTransform: "uppercase", fontFamily: "var(--font-display)", marginBottom: 12
            }}>
                CONFIRMED
              </div>
              <h3 style={{
              fontSize: 24, fontWeight: 700, color: "#F5F3EE", margin: "0 0 24px",
              fontFamily: "var(--font-display)", letterSpacing: "-0.015em", lineHeight: 1.25
            }}>
                We'll see you on the call.
              </h3>
              <div style={{
              height: 600, border: "2px dashed rgba(255,255,255,0.18)", borderRadius: 10,
              display: "flex", alignItems: "center", justifyContent: "center",
              color: "#6A7D8E", fontSize: 14, fontFamily: "var(--font-mono)", textAlign: "center", padding: 20
            }}>
                [ Cal.com booking embed goes here ]
              </div>
            </div> :

          <form onSubmit={submit} noValidate>
              {/* Heading */}
              <h3 style={{
              fontSize: 24, fontWeight: 700, color: "#F5F3EE", margin: "0 0 24px",
              fontFamily: "var(--font-display)", letterSpacing: "-0.015em", lineHeight: 1.25
            }}>A form fill out, you won't regret.

            </h3>

              {/* 1. Owner name */}
              <div style={{ marginBottom: 14 }}>
                <FieldLabel required>Owner name</FieldLabel>
                <input
                type="text"
                data-error={errors.owner ? "1" : undefined}
                style={baseInputStyle(!!errors.owner)}
                value={form.owner}
                onChange={(e) => update("owner", e.target.value)}
                onFocus={focusOn}
                onBlur={focusOff} />
              
                {errors.owner && <div style={{ fontSize: 12, color: "#E85A4A", marginTop: 4 }}>{errors.owner}</div>}
              </div>

              {/* 2. Business name */}
              <div style={{ marginBottom: 14 }}>
                <FieldLabel required>Business name</FieldLabel>
                <input
                type="text"
                data-error={errors.business ? "1" : undefined}
                style={baseInputStyle(!!errors.business)}
                value={form.business}
                onChange={(e) => update("business", e.target.value)}
                onFocus={focusOn}
                onBlur={focusOff} />
              
                {errors.business && <div style={{ fontSize: 12, color: "#E85A4A", marginTop: 4 }}>{errors.business}</div>}
              </div>

              {/* 3. Work email */}
              <div style={{ marginBottom: 14 }}>
                <FieldLabel required>Work email</FieldLabel>
                <input
                type="email"
                data-error={errors.email ? "1" : undefined}
                style={baseInputStyle(!!errors.email)}
                value={form.email}
                onChange={(e) => update("email", e.target.value)}
                onFocus={focusOn}
                onBlur={focusOff} />
              
                {errors.email && <div style={{ fontSize: 12, color: "#E85A4A", marginTop: 4 }}>{errors.email}</div>}
              </div>

              {/* 4. Phone */}
              <div style={{ marginBottom: 14 }}>
                <FieldLabel required>Phone</FieldLabel>
                <input
                type="tel"
                data-error={errors.phone ? "1" : undefined}
                style={baseInputStyle(!!errors.phone)}
                value={form.phone}
                onChange={(e) => update("phone", formatPhone(e.target.value))}
                onFocus={focusOn}
                onBlur={focusOff}
                placeholder="(555) 123-4567" />
              
                {errors.phone && <div style={{ fontSize: 12, color: "#E85A4A", marginTop: 4 }}>{errors.phone}</div>}
              </div>

              {/* 5. Slowdown */}
              <div style={{ marginBottom: 14 }}>
                <FieldLabel>What's the one thing slowing your shop down?</FieldLabel>
                <textarea
                rows={2}
                style={{ ...baseInputStyle(false), resize: "vertical", minHeight: 56, lineHeight: 1.5 }}
                value={form.slowdown}
                onChange={(e) => update("slowdown", e.target.value)}
                onFocus={focusOn}
                onBlur={focusOff} />
              
              </div>

              {/* 6. Calls per week */}
              <div style={{ marginBottom: 24 }}>
                <FieldLabel>How many calls do you get per week?</FieldLabel>
                <select
                style={baseInputStyle(false)}
                value={form.calls}
                onChange={(e) => update("calls", e.target.value)}
                onFocus={focusOn}
                onBlur={focusOff}>
                
                  <option value="" style={{ background: "#0a121d" }}>Select…</option>
                  <option style={{ background: "#0a121d" }}>Under 25</option>
                  <option style={{ background: "#0a121d" }}>25–50</option>
                  <option style={{ background: "#0a121d" }}>50–100</option>
                  <option style={{ background: "#0a121d" }}>100–200</option>
                  <option style={{ background: "#0a121d" }}>200+</option>
                </select>
              </div>

              {/* Submit */}
              <button
              type="submit"
              style={{
                width: "100%",
                padding: "14px 28px",
                background: "#E8934A",
                color: "#080f18",
                border: "none",
                borderRadius: 100,
                fontSize: 15,
                fontWeight: 700,
                cursor: "pointer",
                fontFamily: "var(--font-display)",
                letterSpacing: "-0.01em",
                transition: "all 0.18s",
                boxShadow: "0 2px 0 rgba(0,0,0,0.05)"
              }}
              onMouseEnter={(e) => {e.currentTarget.style.opacity = "0.95";e.currentTarget.style.boxShadow = "0 8px 24px rgba(232,147,74,0.35)";e.currentTarget.style.transform = "translateY(-1px)";}}
              onMouseLeave={(e) => {e.currentTarget.style.opacity = "1";e.currentTarget.style.boxShadow = "0 2px 0 rgba(0,0,0,0.05)";e.currentTarget.style.transform = "translateY(0)";}}>Book the walkthrough →


            </button>

              <p style={{ fontSize: 12, color: "#6A7D8E", textAlign: "center", marginTop: 14, marginBottom: 0, lineHeight: 1.5 }}>20 minutes to save you money.

            </p>
            </form>
          }
        </div>
      </div>
    </div>);

};

Object.assign(window, { AuditPopup });