/* global React, StripeCorner */
const { useState: useStatsState, useEffect: useStatsEffect, useRef: useStatsRef } = React;

function useCountUp(end, duration = 3200) {
  const [count, setCount] = useStatsState(0);
  const ref = useStatsRef(null);
  const started = useStatsRef(false);

  useStatsEffect(() => {
    function isInView(el) {
      const rect = el.getBoundingClientRect();
      return rect.top < window.innerHeight * 0.9 && rect.bottom > 0;
    }

    function start() {
      if (started.current) return;
      started.current = true;
      const startTime = performance.now();
      function tick(now) {
        const elapsed = now - startTime;
        const progress = Math.min(elapsed / duration, 1);
        const eased = 1 - Math.pow(1 - progress, 3);
        setCount(Math.round(eased * end));
        if (progress < 1) requestAnimationFrame(tick);
      }
      requestAnimationFrame(tick);
    }

    const el = ref.current;
    if (!el) return;

    // Primary: IntersectionObserver
    let observer;
    if ('IntersectionObserver' in window) {
      observer = new IntersectionObserver(([entry]) => {
        if (entry.isIntersecting) { start(); observer.disconnect(); }
      }, { threshold: 0.2 });
      observer.observe(el);
    }

    // Fallback: scroll listener + immediate check
    function onScroll() {
      if (isInView(el)) { start(); window.removeEventListener('scroll', onScroll); }
    }
    window.addEventListener('scroll', onScroll, { passive: true });
    if (isInView(el)) start();

    return () => {
      observer && observer.disconnect();
      window.removeEventListener('scroll', onScroll);
    };
  }, [end, duration]);

  return [count, ref];
}

function LogoStrip() {
  const logos = [
    { name: "Lone Star Co.",  style: { fontFamily: "Fraunces, serif", fontWeight: 600, letterSpacing: "-0.02em" } },
    { name: "OAKWELL",        style: { fontFamily: "'Open Sauce Sans', sans-serif", fontWeight: 700, letterSpacing: "0.18em", fontSize: 14 } },
    { name: "Hill & Co.",     style: { fontFamily: "Fraunces, serif", fontStyle: "italic", fontWeight: 500 } },
    { name: "Ridge Realty",   style: { fontFamily: "'Open Sauce Sans', sans-serif", fontWeight: 600, fontSize: 15 } },
    { name: "BRIO",           style: { fontFamily: "Fraunces, serif", fontWeight: 700, letterSpacing: "0.2em" } },
    { name: "Cedar+Co",       style: { fontFamily: "'Open Sauce Sans', sans-serif", fontWeight: 600 } },
  ];
  return (
    <section className="logo-strip" style={{ position: "relative", overflow: "hidden" }}>
      <StripeCorner position="tl" size={160} color="#758766" opacity={0.25}/>
      <StripeCorner position="br" size={160} color="#758766" opacity={0.25}/>
      <div className="container" style={{ position: "relative" }}>
        <div className="logo-strip-label">
          Trusted by small businesses across Austin &amp; Liberty Hill.
        </div>
        <div className="logo-strip-logos">
          {logos.map((l) => (
            <div key={l.name} style={{ ...l.style, color: "#2f1d4b", fontSize: l.style.fontSize || 18 }}>
              {l.name}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function StatItem({ end, suffix, prefix = "", label }) {
  const [count, ref] = useCountUp(end);
  return (
    <div ref={ref}>
      <div className="stat-number">
        {prefix}{count}{suffix}<span className="stat-dot">.</span>
      </div>
      <div className="stat-label">{label}</div>
    </div>
  );
}

function StatRange({ low, high, suffix, label }) {
  const [lo, refLo] = useCountUp(low);
  const [hi, refHi] = useCountUp(high);
  return (
    <div ref={refLo}>
      <div className="stat-number" ref={refHi}>
        {lo}-{hi}{suffix}<span className="stat-dot">.</span>
      </div>
      <div className="stat-label">{label}</div>
    </div>
  );
}

function StatsRow() {
  return (
    <section className="stats-row">
      <div className="container">
        <div className="stats-grid">
          <StatItem end={10} suffix="+" label="Years of office and operations experience."/>
          <StatRange low={8} high={12} suffix=" hrs" label="Saved per client, per week, on average."/>
          <StatItem end={100} suffix="%" label="Remote service across Central Texas."/>
        </div>
      </div>
    </section>
  );
}

function ProblemBlock() {
  const items = [
    { title: "Inbox overload",      body: "You open your email meaning to respond to one thing and lose an hour." },
    { title: "Calendar chaos",      body: "Your day gets away from you before you even start the real work." },
    { title: "Invoices that linger", body: "Billing slips to the bottom of the list, and cash flow pays the price." },
    { title: "Social media silence", body: "You know you should post more, but there is never time to do it well." },
  ];
  return (
    <section className="section">
      <div className="container">
        <div className="problem-card">
          <StripeCorner position="tr" size={260} color="#758766" opacity={0.45}/>
          <StripeCorner position="bl" size={180} color="#c3a8ff" opacity={0.30}/>
          <h2 className="problem-headline">
            Running a business is hard enough. Running the back office on top of it is unsustainable.
          </h2>
          <div className="problem-grid">
            {items.map((it) => (
              <div key={it.title} className="problem-item">
                <div className="problem-item-title">{it.title}</div>
                <div className="problem-item-body">{it.body}</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { LogoStrip, StatsRow, ProblemBlock });
