/* ============================================================
   Reynard Marketing — animated results charts
   Bars (booked jobs/mo), line (cost per job falling),
   horizontal bars (booked jobs by source). All animate on view.
   ============================================================ */

// trigger when the element scrolls into view (once), with safety fallbacks
function useInView() {
  const ref = React.useRef(null);
  const [inView, setInView] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) { setInView(true); return; }
    const root = document.querySelector("#site-scroll");
    const check = () => {
      const r = el.getBoundingClientRect();
      const h = (root ? root.clientHeight : window.innerHeight) || window.innerHeight;
      return r.top < h * 0.88 && r.bottom > 0;
    };
    if (check()) { setInView(true); return; }
    let io;
    try {
      io = new IntersectionObserver((es) => {
        es.forEach((e) => { if (e.isIntersecting) { setInView(true); io.disconnect(); } });
      }, { root, threshold: 0.2 });
      io.observe(el);
    } catch (e) { setInView(true); }
    const t = setTimeout(() => setInView(true), 1600);
    return () => { io && io.disconnect(); clearTimeout(t); };
  }, []);
  return [ref, inView];
}

function useCountUp(target, inView, dur = 1500) {
  const [v, setV] = React.useState(0);
  React.useEffect(() => {
    if (!inView) return;
    let raf, start;
    const ease = (p) => 1 - Math.pow(1 - p, 3);
    const tick = (t) => {
      if (!start) start = t;
      const p = Math.min(1, (t - start) / dur);
      setV(target * ease(p));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [inView, target]);
  return v;
}

const ChartHead = ({ label, children }) => (
  <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: "12px", marginBottom: "20px" }}>
    <div className="eyebrow" style={{ color: "var(--text-on-dark-mute)" }}>{label}</div>
    {children}
  </div>
);

/* ---- Card A: booked jobs per month (vertical bars) ---- */
function BookedJobsCard() {
  const [ref, inView] = useInView();
  const data = [
    ["Oct", 58], ["Nov", 64], ["Dec", 71], ["Jan", 83],
    ["Feb", 96], ["Mar", 112], ["Apr", 128], ["May", 147],
  ];
  const max = 160;
  const count = useCountUp(1800, inView);
  return (
    <Glass ref={ref} style={{ padding: "clamp(24px,2.6vw,34px)", display: "flex", flexDirection: "column" }}>
      <ChartHead label="Booked jobs · monthly">
        <span className="data" style={{ color: "#7FD89A", fontSize: "0.82rem" }}>▲ +312%</span>
      </ChartHead>
      <div style={{ display: "flex", alignItems: "baseline", gap: "10px" }}>
        <span className="data" style={{ fontSize: "clamp(2.4rem,4vw,3.2rem)", color: "var(--amber-400)", lineHeight: 1 }}>
          {Math.round(count).toLocaleString()}+
        </span>
        <span className="small" style={{ color: "var(--text-on-dark-soft)", maxWidth: 170 }}>booked jobs traced to source</span>
      </div>
      <div style={{ display: "flex", alignItems: "flex-end", gap: "clamp(6px,1vw,12px)", height: 140, marginTop: "26px" }}>
        {data.map(([m, v], i) => {
          const hot = i >= data.length - 2;
          return (
            <div key={m} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: "9px", height: "100%", justifyContent: "flex-end" }}>
              <div style={{ width: "100%", display: "flex", alignItems: "flex-end", height: "100%" }}>
                <div style={{
                  width: "100%", borderRadius: "5px 5px 2px 2px",
                  height: inView ? (v / max * 100) + "%" : "0%",
                  background: hot
                    ? "linear-gradient(180deg, var(--amber-400), var(--amber-600))"
                    : "linear-gradient(180deg, var(--steel-400), var(--steel-600))",
                  boxShadow: hot ? "0 0 16px rgba(224,137,47,0.35)" : "none",
                  transition: `height 820ms var(--ease-out) ${i * 70}ms`,
                }} />
              </div>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: "0.66rem", color: "var(--text-on-dark-mute)" }}>{m}</span>
            </div>
          );
        })}
      </div>
    </Glass>
  );
}

/* ---- Card B: cost per job, falling (line + area) ---- */
function CostPerJobCard() {
  const [ref, inView] = useInView();
  const pts = [232, 205, 188, 171, 158, 146, 134, 125]; // $ per job, descending
  const min = 110, max = 250;
  const n = pts.length;
  const X = (i) => (i / (n - 1)) * 100;
  const Y = (v) => 6 + (1 - (v - min) / (max - min)) * 88; // padded 6..94
  const line = pts.map((v, i) => `${i ? "L" : "M"} ${X(i).toFixed(2)} ${Y(v).toFixed(2)}`).join(" ");
  const area = `${line} L 100 100 L 0 100 Z`;
  const drop = useCountUp(46, inView);
  const lastX = X(n - 1), lastY = Y(pts[n - 1]);
  return (
    <Glass ref={ref} style={{ padding: "clamp(24px,2.6vw,34px)", display: "flex", flexDirection: "column" }}>
      <ChartHead label="Cost per booked job">
        <span className="data" style={{ color: "#7FD89A", fontSize: "0.82rem" }}>▼ falling</span>
      </ChartHead>
      <div style={{ display: "flex", alignItems: "baseline", gap: "10px" }}>
        <span className="data" style={{ fontSize: "clamp(2.4rem,4vw,3.2rem)", color: "var(--amber-400)", lineHeight: 1 }}>
          −{Math.round(drop)}%
        </span>
        <span className="small" style={{ color: "var(--text-on-dark-soft)", maxWidth: 180 }}>cost per job since the loop kicked in</span>
      </div>
      <div style={{ position: "relative", height: 150, marginTop: "26px" }}>
        <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ width: "100%", height: "100%", display: "block", overflow: "visible" }}>
          <defs>
            <linearGradient id="cpjFill" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="rgba(224,137,47,0.34)" />
              <stop offset="100%" stopColor="rgba(224,137,47,0)" />
            </linearGradient>
          </defs>
          <path d={area} fill="url(#cpjFill)"
            style={{ opacity: inView ? 1 : 0, transition: "opacity 700ms var(--ease-out) 600ms" }} />
          <path d={line} fill="none" stroke="var(--amber-400)" strokeWidth="2.5"
            vectorEffect="non-scaling-stroke" strokeLinecap="round" strokeLinejoin="round"
            pathLength="1" strokeDasharray="1"
            style={{ strokeDashoffset: inView ? 0 : 1, transition: "stroke-dashoffset 1200ms var(--ease-out)" }} />
        </svg>
        {/* round marker at latest (lowest) cost */}
        <div style={{
          position: "absolute", left: `${lastX}%`, top: `${lastY}%`, transform: "translate(-50%,-50%)",
          width: 12, height: 12, borderRadius: "50%", background: "var(--amber-400)",
          boxShadow: "0 0 0 4px rgba(224,137,47,0.22), 0 0 14px rgba(224,137,47,0.6)",
          opacity: inView ? 1 : 0, transition: "opacity 400ms var(--ease-out) 1100ms",
        }} />
        <span style={{ position: "absolute", left: 0, top: -2, fontFamily: "var(--font-mono)", fontSize: "0.7rem", color: "var(--text-on-dark-mute)" }}>$232</span>
        <span style={{ position: "absolute", right: 0, bottom: 6, fontFamily: "var(--font-mono)", fontSize: "0.7rem", color: "var(--amber-400)" }}>$125</span>
      </div>
    </Glass>
  );
}

/* ---- Card C: booked jobs by source (horizontal bars) ---- */
function BySourceCard() {
  const [ref, inView] = useInView();
  const rows = [
    ["Phone calls · PPC", 44, "var(--amber-500)"],
    ["Local SEO · map pack", 27, "var(--steel-400)"],
    ["Website forms", 19, "var(--steel-500)"],
    ["Funnels", 10, "var(--steel-600)"],
  ];
  return (
    <Glass ref={ref} style={{ padding: "clamp(26px,3vw,40px)" }}>
      <div style={{ display: "grid", gridTemplateColumns: "1.35fr 0.65fr", gap: "clamp(28px,4vw,56px)", alignItems: "center" }} className="split-grid">
        <div>
          <ChartHead label="Every booked job, traced to source" />
          <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
            {rows.map(([label, pct, color], i) => (
              <div key={label}>
                <div style={{ display: "flex", justifyContent: "space-between", marginBottom: "7px" }}>
                  <span className="small" style={{ color: "var(--text-on-dark-soft)" }}>{label}</span>
                  <span className="data" style={{ color: "var(--text-on-dark)", fontSize: "0.85rem" }}>{pct}%</span>
                </div>
                <div style={{ height: 10, borderRadius: "var(--r-pill)", background: "rgba(255,255,255,0.06)", overflow: "hidden" }}>
                  <div style={{
                    height: "100%", borderRadius: "var(--r-pill)", background: color,
                    width: inView ? pct + "%" : "0%",
                    transition: `width 900ms var(--ease-out) ${i * 110}ms`,
                  }} />
                </div>
              </div>
            ))}
          </div>
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
          {[["48", "local businesses on the hunt"], ["100%", "of spend tied to a real call"]].map(([n, l]) => (
            <div key={l} style={{ padding: "18px 20px", borderRadius: "var(--r-md)",
              background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.08)" }}>
              <div className="data" style={{ fontSize: "clamp(1.8rem,2.6vw,2.3rem)", color: "var(--amber-400)", lineHeight: 1 }}>{n}</div>
              <div className="small" style={{ color: "var(--text-on-dark-soft)", marginTop: "7px" }}>{l}</div>
            </div>
          ))}
        </div>
      </div>
    </Glass>
  );
}

/* ---- Results section ---- */
function Results({ motion }) {
  return (
    <section id="results" style={{ padding: "clamp(34px,5vw,80px) clamp(16px,4vw,40px)" }}>
      <div style={{ maxWidth: MAXW, margin: "0 auto" }}>
        <Reveal enabled={motion}>
          <div style={{ maxWidth: 640, marginBottom: "clamp(22px,3vw,38px)" }}>
            <Eyebrow>Results</Eyebrow>
            <h2 className="h1" style={{ color: "var(--text-on-dark)", margin: "14px 0 0" }}>
              Numbers that pay you back.
            </h2>
          </div>
        </Reveal>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "18px" }} className="reviews-grid">
          <BookedJobsCard />
          <CostPerJobCard />
        </div>
        <div style={{ marginTop: "18px" }}>
          <BySourceCard />
        </div>
        <div className="small" style={{ color: "var(--text-on-dark-mute)", marginTop: "20px",
          fontFamily: "var(--font-mono)", fontSize: "0.78rem", opacity: 0.85 }}>
          Illustrative figures — we report your real booked jobs and cost per job every month.
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Results });
