/* ============================================================
   Reynard Marketing — homepage sections
   Single scrolling page. Every word sits on glass; bare
   engraving shows only in the gaps (atmosphere bands).
   ============================================================ */

const MAXW = 1180;
const smoothTo = (id) => {
  const root = document.querySelector("#site-scroll");
  const el = document.getElementById(id);
  if (!root || !el) return;
  root.scrollTo({ top: el.offsetTop - 90, behavior: "smooth" });
};

/* ---------------- NAV ---------------- */
function Nav({ onBook, links }) {
  const [scrolled, setScrolled] = React.useState(false);
  const [open, setOpen] = React.useState(false);
  React.useEffect(() => {
    const el = document.querySelector("#site-scroll");
    const fn = () => setScrolled((el?.scrollTop || 0) > 30);
    el?.addEventListener("scroll", fn);
    return () => el?.removeEventListener("scroll", fn);
  }, []);
  return (
    <div style={{ position: "sticky", top: 0, zIndex: 50, padding: "16px clamp(16px,4vw,40px)" }}>
      <Glass style={{
        display: "flex", alignItems: "center", justifyContent: "space-between",
        padding: "12px 14px 12px 22px", borderRadius: "var(--r-pill)",
        transition: "background var(--dur)",
        background: scrolled ? "var(--glass-dark-bg-strong)" : "var(--glass-dark-bg)",
      }}>
        <a href="#top" onClick={(e) => { e.preventDefault(); smoothTo("top"); }} style={{ display: "flex" }}>
          <Wordmark variant="light" height={22} />
        </a>
        <nav style={{ display: "flex", gap: "28px", alignItems: "center" }} className="nav-links">
          {links.map((l) => <NavLink key={l.id} label={l.label} target={l.id} />)}
        </nav>
        <div style={{ display: "flex", gap: "10px", alignItems: "center" }}>
          <a href="tel:+18005550199" style={{
            fontFamily: "var(--font-mono)", fontWeight: 700, fontSize: "0.9rem",
            color: "var(--text-on-dark-soft)", textDecoration: "none",
            display: "flex", alignItems: "center", gap: "8px",
          }} className="nav-phone">
            <span style={{ color: "var(--amber-400)" }}>{Icon.phone({ s: 18 })}</span>
            (800) 555-0199
          </a>
          <AmberButton onClick={onBook} style={{ padding: "11px 20px", fontSize: "0.95rem" }}>
            Book a call
          </AmberButton>
          <button className="nav-burger" onClick={() => setOpen((o) => !o)} aria-label="Menu" style={{
            display: "none", background: "rgba(255,255,255,0.06)", border: "1px solid var(--glass-dark-border)",
            color: "var(--text-on-dark)", borderRadius: "var(--r-sm)", padding: "9px", cursor: "pointer",
          }}>{open ? Icon.x({ s: 20 }) : Icon.menu({ s: 20 })}</button>
        </div>
      </Glass>
      {open && (
        <Glass style={{ marginTop: "10px", padding: "10px", display: "none", flexDirection: "column" }} className="nav-drawer">
          {links.map((l) => (
            <a key={l.id} href={`#${l.id}`} onClick={(e) => { e.preventDefault(); smoothTo(l.id); setOpen(false); }}
              style={{ padding: "13px 16px", color: "var(--text-on-dark-soft)", textDecoration: "none",
                fontFamily: "var(--font-body)", fontWeight: 500, borderRadius: "var(--r-sm)" }}>{l.label}</a>
          ))}
        </Glass>
      )}
    </div>
  );
}
function NavLink({ label, target }) {
  const [h, setH] = React.useState(false);
  return (
    <a href={`#${target}`} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      onClick={(e) => { e.preventDefault(); smoothTo(target); }}
      style={{
        fontFamily: "var(--font-body)", fontWeight: 500, fontSize: "0.96rem",
        color: h ? "var(--text-on-dark)" : "var(--text-on-dark-soft)",
        textDecoration: "none", transition: "color var(--dur)",
      }}>{label}</a>
  );
}

/* ---------------- HERO ---------------- */
function Hero({ onBook, layout, ticker, motion }) {
  const centered = layout === "centered";
  return (
    <section id="top" style={{ padding: "clamp(40px,7vw,96px) clamp(16px,4vw,40px) clamp(30px,5vw,64px)" }}>
      <div style={{
        maxWidth: MAXW, margin: "0 auto", display: "grid",
        gridTemplateColumns: centered ? "1fr" : "1.12fr 0.88fr",
        gap: "28px", alignItems: "stretch", justifyItems: centered ? "center" : "stretch",
      }} className="hero-grid">
        <Reveal enabled={motion} style={{ display: "flex" }}>
          <Glass strong style={{
            padding: "clamp(30px,3.6vw,54px)", display: "flex", flexDirection: "column",
            justifyContent: "center", maxWidth: centered ? 760 : "none", textAlign: centered ? "center" : "left",
            alignItems: centered ? "center" : "stretch", width: "100%",
          }}>
            <Eyebrow>Lead-gen for local service businesses</Eyebrow>
            <h1 className="h-display" style={{ margin: "18px 0 0", color: "var(--text-on-dark)" }}>
              We hunt.<br />You book.
            </h1>
            <div className="glass__readband" style={{ marginTop: "26px", padding: "18px 20px", maxWidth: 560 }}>
              <p className="lead" style={{ margin: 0, color: "var(--text-on-dark-soft)" }}>
                Reynard Marketing brings local service businesses more booked jobs — through
                PPC, SEO, websites, and funnels built to track every dollar back to a real phone call.
              </p>
            </div>
            <div style={{ display: "flex", gap: "12px", marginTop: "28px", flexWrap: "wrap", justifyContent: centered ? "center" : "flex-start" }}>
              <AmberButton onClick={onBook}>Book a free strategy call {Icon.arrow({ s: 18 })}</AmberButton>
              <GhostButton onClick={() => smoothTo("results")}>See the catch</GhostButton>
            </div>
            <div style={{ display: "flex", gap: "26px", marginTop: "32px", flexWrap: "wrap", justifyContent: centered ? "center" : "flex-start" }}>
              {[["Booked jobs", "the metric we lead with"], ["Every $", "tracked to a real phone call"], ["24h", "to your first strategy call"]].map(([n, l]) => (
                <div key={l} style={{ minWidth: 92 }}>
                  <div className="data" style={{ fontSize: n.length > 6 ? "1.15rem" : "1.5rem", color: "var(--amber-400)", lineHeight: 1.1 }}>{n}</div>
                  <div className="small" style={{ color: "var(--text-on-dark-mute)", maxWidth: 150, marginTop: 4 }}>{l}</div>
                </div>
              ))}
            </div>
          </Glass>
        </Reveal>
        {!centered && (
          <Reveal enabled={motion} delay={120} style={{ display: "flex" }}>
            <CallTrackingCard ticker={ticker} />
          </Reveal>
        )}
      </div>
    </section>
  );
}

/* ---------------- LIVE CALL-TRACKING CARD ---------------- */
const ALL_LEADS = [
  { type: "Phone call",      icon: Icon.phone, channel: "Google PPC · “emergency plumber”", status: "Booked", value: 1840 },
  { type: "Form submission", icon: Icon.form,  channel: "Website · “book online” form",      status: "Booked", value: 980 },
  { type: "Website lead",    icon: Icon.globe, channel: "Local SEO · map pack",              status: "Booked", value: 640 },
  { type: "Form submission", icon: Icon.form,  channel: "Funnel · spring AC tune-up",         status: "Quoted", value: 320 },
  { type: "Phone call",      icon: Icon.phone, channel: "Google PPC · “water heater repair”", status: "Booked", value: 2200 },
  { type: "Website lead",    icon: Icon.globe, channel: "Local SEO · “roof leak near me”",    status: "Booked", value: 1450 },
  { type: "Phone call",      icon: Icon.phone, channel: "Chat widget · “need a quote”",        status: "Quoted", value: 410 },
];
const BASE = ALL_LEADS.slice(0, 4);
const BASE_BOOKED = BASE.filter((l) => l.status === "Booked").length;
const BASE_TOTAL = BASE.filter((l) => l.status === "Booked").reduce((a, l) => a + l.value, 0);
function CallTrackingCard({ ticker }) {
  const [rows, setRows] = React.useState(BASE);
  const [total, setTotal] = React.useState(BASE_TOTAL);
  const [booked, setBooked] = React.useState(BASE_BOOKED);
  const [pulse, setPulse] = React.useState(false);
  const idx = React.useRef(4);
  React.useEffect(() => {
    if (!ticker) { setRows(BASE); setTotal(BASE_TOTAL); setBooked(BASE_BOOKED); return; }
    const iv = setInterval(() => {
      // loop in a believable range — reset after a full pass so the sample
      // never climbs into implausible territory
      if (idx.current >= ALL_LEADS.length + 4) {
        idx.current = 4;
        setRows(BASE); setTotal(BASE_TOTAL); setBooked(BASE_BOOKED);
        return;
      }
      const next = ALL_LEADS[idx.current % ALL_LEADS.length];
      idx.current += 1;
      setRows((r) => [next, ...r].slice(0, 4));
      if (next.status === "Booked") { setTotal((t) => t + next.value); setBooked((b) => b + 1); }
      setPulse(true);
      setTimeout(() => setPulse(false), 700);
    }, 3200);
    return () => clearInterval(iv);
  }, [ticker]);
  const fmt = (n) => "$" + n.toLocaleString();
  return (
    <Glass style={{ padding: "22px 22px 8px", display: "flex", flexDirection: "column", width: "100%" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <Eyebrow color="var(--text-on-dark-mute)">Your lead dashboard</Eyebrow>
        <span style={{ display: "inline-flex", alignItems: "center", gap: "7px", fontFamily: "var(--font-mono)", fontSize: "0.72rem", letterSpacing: "0.12em",
          color: "var(--text-on-dark-mute)", border: "1px solid var(--glass-dark-border)", borderRadius: "var(--r-pill)", padding: "4px 10px" }}>
          <span style={{ width: 7, height: 7, borderRadius: "50%", background: "#7FD89A",
            boxShadow: "0 0 9px #7FD89A", animation: ticker ? "rk-blink 1.6s var(--ease-in-out) infinite" : "none" }} />SAMPLE
        </span>
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: "10px", marginTop: "14px" }}>
        <span className="data" style={{ fontSize: "2.6rem", color: "var(--amber-400)",
          transition: "text-shadow var(--dur)", textShadow: pulse ? "0 0 22px rgba(224,137,47,0.55)" : "none" }}>{booked}</span>
        <span className="small" style={{ color: "var(--text-on-dark)", fontWeight: 700 }}>jobs booked</span>
        <span className="small" style={{ color: "var(--text-on-dark-mute)", fontFamily: "var(--font-mono)", marginLeft: "auto" }}>{fmt(total)} tracked</span>
      </div>
      <div style={{ marginTop: "12px", display: "flex", flexDirection: "column", gap: "8px", flex: 1 }}>
        {rows.map((lead, i) => (
          <div key={lead.channel + i} style={{
            display: "flex", alignItems: "center", gap: "11px",
            padding: "10px 12px", borderRadius: "var(--r-sm)",
            background: i === 0 && ticker ? "rgba(127,216,154,0.10)" : "rgba(255,255,255,0.05)",
            border: `1px solid ${i === 0 && ticker ? "rgba(127,216,154,0.28)" : "rgba(255,255,255,0.08)"}`,
            transition: "background 500ms var(--ease-out), border-color 500ms var(--ease-out)",
            animation: i === 0 && ticker ? "rk-slidein 460ms var(--ease-out)" : "none",
          }}>
            <span style={{ width: 30, height: 30, borderRadius: "8px", flexShrink: 0, display: "grid", placeItems: "center",
              background: "rgba(224,137,47,0.13)", border: "1px solid rgba(224,137,47,0.28)", color: "var(--amber-400)" }}>
              {lead.icon({ s: 16 })}
            </span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="small" style={{ color: "var(--text-on-dark)", fontWeight: 700, lineHeight: 1.2 }}>{lead.type}</div>
              <div style={{ color: "var(--text-on-dark-mute)", fontSize: "0.76rem", lineHeight: 1.25, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{lead.channel}</div>
            </div>
            <span style={{ fontFamily: "var(--font-mono)", fontSize: "0.62rem", letterSpacing: "0.08em", textTransform: "uppercase", flexShrink: 0,
              color: lead.status === "Booked" ? "#7FD89A" : "var(--text-on-dark-mute)" }}>{lead.status}</span>
            <span className="data" style={{ fontSize: "0.92rem", color: "var(--text-on-dark)", width: 60, textAlign: "right", flexShrink: 0 }}>{fmt(lead.value)}</span>
          </div>
        ))}
      </div>
      <div style={{ borderTop: "1px solid rgba(255,255,255,0.1)", margin: "8px 0 0", padding: "13px 2px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <span className="small" style={{ color: "var(--text-on-dark-mute)" }}>Example dashboard · your real leads land here</span>
        <span style={{ color: "var(--text-on-dark-soft)" }}>{Icon.waveform({ s: 22 })}</span>
      </div>
    </Glass>
  );
}

/* ---------------- PROBLEM ---------------- */
function Problem({ motion }) {
  const vanity = ["Impressions", "Clicks", "“Engagement”", "Reach", "Likes", "Page views"];
  return (
    <section style={{ padding: "clamp(30px,5vw,72px) clamp(16px,4vw,40px)" }}>
      <div style={{ maxWidth: MAXW, margin: "0 auto" }}>
        <Reveal enabled={motion}>
          <Glass style={{ padding: "clamp(28px,3.6vw,56px)", display: "grid",
            gridTemplateColumns: "1.1fr 0.9fr", gap: "clamp(24px,3vw,48px)", alignItems: "center" }} className="split-grid">
            <div>
              <Eyebrow>The problem</Eyebrow>
              <h2 className="h1" style={{ color: "var(--text-on-dark)", margin: "14px 0 16px" }}>
                Most agencies can’t tell you what your money did.
              </h2>
              <p className="body" style={{ color: "var(--text-on-dark-soft)", margin: 0, fontSize: "1.05rem", maxWidth: 520 }}>
                You get a report full of numbers that look busy and prove nothing. Impressions.
                Clicks. “Engagement.” None of it tells you whether the phone rang, or whether the
                job got booked. You’re paying for motion, not results.
              </p>
              <p className="body" style={{ color: "var(--text-on-dark)", margin: "16px 0 0", fontSize: "1.05rem", fontWeight: 600, maxWidth: 520 }}>
                A booked job is the only number that pays you back. That’s the only one we count.
              </p>
            </div>
            <div className="glass__readband" style={{ padding: "22px 22px 8px" }}>
              <div className="small" style={{ color: "var(--text-on-dark-mute)", fontFamily: "var(--font-mono)", letterSpacing: "0.06em", textTransform: "uppercase", marginBottom: "14px" }}>
                What other agencies report
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: "2px" }}>
                {vanity.map((v) => (
                  <div key={v} style={{ display: "flex", alignItems: "center", justifyContent: "space-between",
                    padding: "11px 2px", borderBottom: "1px solid rgba(255,255,255,0.07)" }}>
                    <span style={{ display: "inline-flex", alignItems: "center", gap: "11px", color: "var(--text-on-dark-mute)" }}>
                      <span style={{ color: "var(--steel-400)", opacity: 0.7 }}>{Icon.eyeOff({ s: 18 })}</span>
                      <span className="body" style={{ textDecoration: "line-through", textDecorationColor: "rgba(143,166,189,0.5)" }}>{v}</span>
                    </span>
                    <span className="data" style={{ fontSize: "0.78rem", color: "var(--steel-400)" }}>vanity</span>
                  </div>
                ))}
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "15px 2px 6px" }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: "11px" }}>
                    <span style={{ color: "var(--amber-400)" }}>{Icon.check({ s: 18 })}</span>
                    <span className="body" style={{ color: "var(--text-on-dark)", fontWeight: 700 }}>Booked jobs</span>
                  </span>
                  <span className="data" style={{ fontSize: "0.78rem", color: "var(--amber-400)" }}>what we count</span>
                </div>
              </div>
            </div>
          </Glass>
        </Reveal>
      </div>
    </section>
  );
}

Object.assign(window, { MAXW, smoothTo, Nav, Hero, CallTrackingCard, Problem });
