/* global React */
const { useState: useStateCS, useEffect: useEffectCS, useRef: useRefCS } = React;

/* ---------- Inline arrow icon ---------- */
const ArrowSvg = () => (
  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
       strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
    <path d="M7 7h10v10"/><path d="M7 17 17 7"/>
  </svg>
);

/**
 * CountUp — animates a number from 0 to `to` when it enters the viewport.
 * Pass a `format` function for prefixes/suffixes/decimals.
 */
function CountUp({ to, format = (v) => Math.round(v).toString(), duration = 1400, delay = 0 }) {
  const [v, setV] = useStateCS(0);
  const ref = useRefCS(null);

  useEffectCS(() => {
    const el = ref.current;
    if (!el) return;
    let raf = 0;
    let active = false;

    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting && !active) {
            active = true;
            setV(0);
            const startTime = performance.now() + delay;
            const tick = (now) => {
              if (now < startTime) {
                raf = requestAnimationFrame(tick);
                return;
              }
              const t = Math.min(1, (now - startTime) / duration);
              const eased = 1 - Math.pow(1 - t, 3);
              setV(to * eased);
              if (t < 1) raf = requestAnimationFrame(tick);
            };
            raf = requestAnimationFrame(tick);
          } else if (!e.isIntersecting) {
            // Reset so a fresh count-up plays next time the element re-enters
            active = false;
            cancelAnimationFrame(raf);
          }
        });
      },
      { threshold: 0.4 }
    );
    io.observe(el);
    return () => {
      io.disconnect();
      cancelAnimationFrame(raf);
    };
  }, [to, duration, delay]);

  return <span ref={ref}>{format(v)}</span>;
}

function CaseStudies() {
  return (
    <section className="at-section at-cases" id="work">
      <div className="at-container">
        <div className="at-cases-head" style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 56, gap: 32, flexWrap: 'wrap' }}>
          <div>
            <div className="at-eyebrow">Selected work</div>
            <h2 className="at-h-section">Systems we shipped<br />this year.</h2>
          </div>
          <a href="/case-studies" className="at-btn at-btn--ghost-dark" data-cursor-label="all work">
            All case studies
            <ArrowSvg />
          </a>
        </div>

        <div className="at-cases-grid">
          {/* LEFT — Featured: Fintech SaaS */}
          <article className="at-case-featured at-reveal-card" data-cursor-label="case study · fintech">
            <div className="at-case-meta">
              <span>Fintech SaaS · 2026</span>
              <span className="tag">Automation · Production</span>
            </div>

            <div className="at-case-big-num">
              <CountUp to={360} duration={2400} format={(v) => `$${Math.round(v)}K`} />
              <small>+</small>
            </div>
            <div className="at-case-big-label">Annual saving</div>

            <h3 className="at-case-h">
              Advisor onboarding from 2–3 days to under 5 minutes.
            </h3>
            <p className="at-case-desc">
              A 70-step automation across 10+ platforms provisions a complete branded GHL CRM, course access, credentials, nurture campaigns, and a live 30-metric analytics dashboard from a single form. Token rotation and dynamic field mapping keep it running through schema changes.
            </p>
            <a href="/case-study-advisor-onboarding" target="_blank" rel="noopener" className="at-case-link" data-cursor-label="read writeup">
              Read the writeup <ArrowSvg />
            </a>

            <div className="at-case-stats">
              <div className="at-case-stat">
                <div className="at-case-stat-num">
                  <CountUp to={95} duration={1800} delay={400} format={(v) => `${Math.round(v)}%`} />
                </div>
                <div className="at-case-stat-lbl">Time cut</div>
              </div>
              <div className="at-case-stat">
                <div className="at-case-stat-num">
                  <CountUp to={360} duration={1800} delay={600} format={(v) => `$${Math.round(v)}K+`} />
                </div>
                <div className="at-case-stat-lbl">Annual saving</div>
              </div>
              <div className="at-case-stat">
                <div className="at-case-stat-num">
                  <CountUp to={100} duration={1800} delay={800} format={(v) => `${Math.round(v)}%`} />
                </div>
                <div className="at-case-stat-lbl">Config accuracy</div>
              </div>
              <div className="at-case-stat">
                <div className="at-case-stat-num">
                  <CountUp to={98} duration={1800} delay={1000} format={(v) => `${Math.round(v)}%+`} />
                </div>
                <div className="at-case-stat-lbl">Success rate</div>
              </div>
            </div>
          </article>

          {/* RIGHT — sticky-stack of two mini cases */}
          <div className="at-cases-stack">
            <article className="at-case-mini at-reveal-card" style={{ '--i': 0 }} data-cursor-label="case study · klinically">
              <div className="at-case-mini-meta">
                <span>Klinically · MedSpa · 2026</span>
                <span className="tag">GHL · Production</span>
              </div>
              <div className="at-case-mini-num">
                <CountUp to={400} duration={2000} delay={250} format={(v) => `${Math.round(v)}`} />
                <small>+ flows</small>
              </div>
              <h3 className="at-case-mini-h">
                The most comprehensive MedSpa automation built on GoHighLevel.
              </h3>
              <p className="at-case-mini-desc">
                190 treatment calendars, 130 forms (43 consent + 87 aftercare), and 400+ workflows across 100+ treatments. Deploys production-ready in under 20 minutes versus the usual 4–6 weeks of manual setup.
              </p>
              <a href="/case-study-klinically" className="at-case-mini-link" data-cursor-label="read writeup">
                Read the writeup <ArrowSvg />
              </a>
            </article>

            <article className="at-case-mini at-reveal-card" style={{ '--i': 1 }} data-cursor-label="case study · sonigo">
              <div className="at-case-mini-meta">
                <span>Sonigo · 2025</span>
                <span className="tag">AI Agent · Outreach</span>
              </div>
              <div className="at-case-mini-num">
                <CountUp to={7} duration={2000} delay={250} format={(v) => `${Math.round(v)}`} />
                <small>day build</small>
              </div>
              <h3 className="at-case-mini-h">
                An AI LinkedIn concierge that qualifies leads 24/7 — built in 7 days.
              </h3>
              <p className="at-case-mini-desc">
                Reads inbound LinkedIn messages with GPT, scores intent, validates emails, dedupes across accounts, and routes only sales-ready leads into GHL with full conversation context. Responds in 2–3 minutes, around the clock.
              </p>
              <a href="/case-study-linkedin-concierge" className="at-case-mini-link" data-cursor-label="read writeup">
                Read the writeup <ArrowSvg />
              </a>
            </article>
          </div>
        </div>
      </div>
    </section>
  );
}

window.CaseStudies = CaseStudies;
