// ===== Custom logo, payout counter, sticky CTA, exit intent =====

// ---------- Custom Logo ----------
function Logo({ size = 44, layout = "horizontal", tone = "dark" }) {
  // tone: "dark" = light text on dark bg; "light" = inverse
  const txtColor = tone === "dark" ? "var(--cream)" : "var(--ink)";
  const subColor = tone === "dark" ? "var(--gold-2)" : "var(--gold-3)";
  return (
    <div className={"logo logo-" + layout} aria-label="Gold Buying Experts">
      <svg width={size} height={size} viewBox="0 0 64 64" className="logo-mark" aria-hidden="true">
        <defs>
          <linearGradient id="lg-gold" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="#f0d088" />
            <stop offset="0.55" stopColor="#c9a24b" />
            <stop offset="1" stopColor="#8b6b22" />
          </linearGradient>
          <linearGradient id="lg-inner" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="#1a2030" />
            <stop offset="1" stopColor="#0a0d16" />
          </linearGradient>
        </defs>
        {/* Outer gold ring */}
        <circle cx="32" cy="32" r="30" fill="url(#lg-gold)" />
        {/* Inner ink disc */}
        <circle cx="32" cy="32" r="26" fill="url(#lg-inner)" />
        {/* Thin gold accent ring */}
        <circle cx="32" cy="32" r="22.5" fill="none" stroke="#c9a24b" strokeWidth="0.6" opacity="0.55" />
        {/* Serif G */}
        <text x="32" y="42.5" textAnchor="middle"
          fontFamily="Cormorant Garamond, Georgia, serif"
          fontWeight="500" fontSize="34"
          fill="url(#lg-gold)">G</text>
        {/* Gold bar accent under the G */}
        <rect x="22" y="48.5" width="20" height="1.4" fill="#c9a24b" opacity="0.85" />
        <rect x="26" y="51.5" width="12" height="1" fill="#c9a24b" opacity="0.55" />
      </svg>
      <div className="logo-words" style={{ color: txtColor }}>
        <span className="wm-top" style={{ color: subColor }}>GOLD BUYING</span>
        <span className="wm-bot">Experts</span>
      </div>
    </div>
  );
}

// ---------- Top trust strip (replaces spot-price bar) ----------
function TrustStrip() {
  const items = [
    { icon: <I.ShieldCheck size={14} />, text: "BBB A+ Accredited since 2009" },
    { icon: <I.Truck size={14} />, text: "Free FedEx kit · $100,000 insured" },
    { icon: <I.Clock size={14} />, text: "Paid within 24 hours of acceptance" },
    { icon: <I.Award size={14} />, text: "GIA-certified appraisers on staff" },
    { icon: <I.Star size={12} />, text: "4.9 / 5-12,847 verified reviews" },
  ];
  return (
    <div className="trust-strip">
      <div className="container trust-strip-inner">
        <div className="trust-marquee">
          {items.concat(items).map((it, i) => (
            <span className="trust-item" key={i}>{it.icon}<span>{it.text}</span></span>
          ))}
        </div>
      </div>
    </div>
  );
}

// ---------- Nav ----------
function Nav() {
  return (
    <div className="nav">
      <div className="container nav-inner">
        <Logo size={48} layout="horizontal" tone="dark" />
        <div className="nav-trust">
          <span className="item"><I.ShieldCheck size={16} /> BBB A+ Accredited</span>
          <span className="item"><I.Star size={14} /> 4.9 / 5 · 12,847 reviews</span>
          <span className="item"><I.Truck size={16} /> $100,000 Insured</span>
        </div>
        <button className="nav-cta" onClick={() => {
          const el = document.getElementById("form-card");
          if (el) window.scrollTo({ top: el.offsetTop - 60, behavior: "smooth" });
        }}>
          Get Free Kit <I.ArrowRight size={14} stroke={2.4} />
        </button>
      </div>
    </div>
  );
}

// ---------- Animated payout counter ----------
function useAnimatedNumber(target, duration = 2000, start = 0) {
  const [val, setVal] = React.useState(start);
  React.useEffect(() => {
    let raf;
    const t0 = performance.now();
    const tick = (now) => {
      const t = Math.min(1, (now - t0) / duration);
      const eased = 1 - Math.pow(1 - t, 3);
      setVal(start + (target - start) * eased);
      if (t < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [target, duration, start]);
  return val;
}

function PayoutCounter() {
  const [target, setTarget] = React.useState(347_281_492);
  const value = useAnimatedNumber(target, 1600);
  React.useEffect(() => {
    const id = setInterval(() => {
      setTarget((v) => v + Math.floor(40 + Math.random() * 260));
    }, 5800);
    return () => clearInterval(id);
  }, []);
  const fmt = (n) => "$" + Math.floor(n).toLocaleString("en-US");
  return (
    <div className="payout-counter">
      <div className="pc-deco" aria-hidden="true">
        <div className="pc-bar pc-bar-1"></div>
        <div className="pc-bar pc-bar-2"></div>
        <div className="pc-bar pc-bar-3"></div>
      </div>
      <div>
        <div className="eyebrow">Lifetime payouts to customers</div>
        <div className="big-num">{fmt(value)}</div>
        <div className="big-label">and counting, updated in real time</div>
      </div>
      <div className="row">
        <div>
          <div className="k">17 yrs</div>
          <div className="l">In business since 2008</div>
        </div>
        <div>
          <div className="k">128k+</div>
          <div className="l">Happy customers</div>
        </div>
        <div>
          <div className="k">A+</div>
          <div className="l">BBB rating</div>
        </div>
        <div>
          <div className="k">4.9★</div>
          <div className="l">Trustpilot · Google</div>
        </div>
      </div>
    </div>
  );
}

// ---------- Sticky CTA bar ----------
function StickyCTA({ slotsLeft }) {
  const [show, setShow] = React.useState(false);
  const [dismissed, setDismissed] = React.useState(false);
  const [formInView, setFormInView] = React.useState(false);

  // Track form visibility via IntersectionObserver so we can suppress the
  // sticky bottom CTA whenever the actual form is on screen, no point
  // showing two competing CTAs.
  React.useEffect(() => {
    const el = document.getElementById("form-card");
    if (!el || typeof IntersectionObserver === "undefined") return;
    const obs = new IntersectionObserver(
      (entries) => setFormInView(entries[0].isIntersecting),
      { threshold: 0.15 }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  React.useEffect(() => {
    const onScroll = () => {
      if (dismissed) return;
      setShow(window.scrollY > 900);
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, [dismissed]);

  // Final visibility = scrolled past threshold AND form NOT in viewport
  const visible = show && !formInView;

  const scrollToForm = () => {
    const formCard = document.getElementById("form-card");
    if (!formCard) return;
    const firstInput = formCard.querySelector("input, select");
    if (firstInput) {
      const r = firstInput.getBoundingClientRect();
      const targetY = Math.max(0, window.scrollY + r.top - 240);
      window.scrollTo({ top: targetY, behavior: "smooth" });
    } else {
      window.scrollTo({ top: formCard.offsetTop - 60, behavior: "smooth" });
    }
  };

  return (
    <div className={"sticky-cta " + (visible ? "show" : "")}>
      <div className="container sticky-cta-inner">
        <div className="sticky-left">
          <div className="sticky-mark" aria-hidden="true">
            <Logo size={36} layout="mark-only" tone="dark" />
          </div>
          <div className="text">
            <span className="label">Get the highest payout for your gold.</span>
            <span className="sub"><b>{slotsLeft}</b> same-day slots remain · Free insured kit · Paid in 24 hrs</span>
          </div>
        </div>
        <div className="actions">
          <button className="cta" onClick={scrollToForm}>Claim Free Kit <I.ArrowRight size={14} stroke={2.4} /></button>
        </div>
      </div>
    </div>
  );
}

// ---------- Exit-intent popup ----------
function ExitIntent({ onClaim }) {
  const [open, setOpen] = React.useState(false);
  const fired = React.useRef(false);

  // Suppression check. NEVER fire while the user is actively engaged with
  // the lead form. Engagement counts as any of:
  //   1. Focus is inside #form-card (typing right now)
  //   2. Any input/select inside #form-card has a value (started filling)
  //   3. The form has moved past step 1 (uploading photos / on success state)
  //
  // We re-check at the moment of fire so a user who starts filling at second
  // 49 won't have the popup punish them at second 50.
  const isFormEngaged = () => {
    const formCard = document.getElementById("form-card");
    if (!formCard) return false;
    // Past step 1?
    const step = formCard.getAttribute("data-step");
    if (step && step !== "1") return true;
    // Focused inside the form?
    const active = document.activeElement;
    if (active && formCard.contains(active) && active !== document.body) return true;
    // Any field with content?
    const fields = formCard.querySelectorAll("input, select, textarea");
    for (const f of fields) {
      if (f.type === "hidden") continue;
      if (f.tagName === "SELECT") { if (f.value && f.value !== "") return true; }
      else if (f.value && f.value.trim() !== "") return true;
    }
    return false;
  };

  React.useEffect(() => {
    if (sessionStorage.getItem("gbe-exit-shown")) { fired.current = true; return; }
    const tryFire = (reason) => {
      if (fired.current) return;
      if (isFormEngaged()) return; // never interrupt an active fill
      fired.current = true;
      sessionStorage.setItem("gbe-exit-shown", "1");
      setOpen(true);
    };
    const onLeave = (e) => {
      if (e.clientY <= 4) tryFire("mouseout");
    };
    // Idle timer, only fires if user hasn't engaged with the form yet
    const timer = setTimeout(() => tryFire("timeout"), 50000);
    document.addEventListener("mouseout", onLeave);
    return () => {
      document.removeEventListener("mouseout", onLeave);
      clearTimeout(timer);
    };
  }, []);

  if (!open) return null;
  const close = () => setOpen(false);
  const claim = () => { close(); onClaim && onClaim(); };

  return (
    <div className="modal-backdrop" onClick={close}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <button className="close" onClick={close} aria-label="Close"><I.X size={16} stroke={2.4} /></button>
        <div className="head">
          <div className="modal-badge"><Logo size={48} layout="mark-only" tone="dark" /></div>
          <div className="eyebrow">Wait, before you go</div>
          <h3>Claim a <em>$50 bonus</em> on your first appraisal</h3>
          <p>Leave your email and we'll add a $50 bonus to whatever offer we send, yours to keep, no obligation.</p>
        </div>
        <div className="body">
          <ul>
            <li><I.Check size={16} stroke={2.4} /> <span><strong>+$50 added</strong> automatically to your final offer.</span></li>
            <li><I.Check size={16} stroke={2.4} /> <span><strong>Free insured FedEx kit</strong> $100,000 coverage included.</span></li>
            <li><I.Check size={16} stroke={2.4} /> <span><strong>Don't like the offer?</strong> We ship everything back free.</span></li>
            <li><I.Check size={16} stroke={2.4} /> <span><strong>Paid in 24 hours</strong> by Zelle, ACH, PayPal, wire, or check.</span></li>
          </ul>
          <button className="cta-btn" onClick={claim}>Claim My $50 Bonus <I.ArrowRight size={16} stroke={2.4} style={{ verticalAlign: "-3px" }} /></button>
          <div className="small">256-bit secure · No card · One-time offer per household</div>
        </div>
      </div>
    </div>
  );
}

window.Logo = Logo;
window.TrustStrip = TrustStrip;
window.Nav = Nav;
window.PayoutCounter = PayoutCounter;
window.StickyCTA = StickyCTA;
window.ExitIntent = ExitIntent;
