// Testimonials.jsx — "Client proof" auto-advancing carousel, tuned for the
// audit-first CRO offer: Shopify, ecommerce optimization, audits, and roadmaps.
// Shows ~3 cards + a faded 4th; advances every 5s, loops seamlessly, pauses on hover.
// Card: client logo (top-left) + stars (top-right), proof headline, quote, theme tags,
// divider, then headshot + name · role · company. Drop headshots at assets/headshots/.
function TsStars() {
  return <span className="ts-stars" aria-label="5 out of 5">{"\u2605\u2605\u2605\u2605\u2605"}</span>;
}
function TsRating({ source }) {
  const plat = source === "Clutch" ? "clutch-wordmark" : source === "Trustpilot" ? "trustpilot-wordmark" : null;
  return (
    <div className="ts-rating">
      <span className="ts-rating-row"><TsStars /><span className="ts-score">5.0</span></span>
      {plat && <img className="ts-plat" src={assetUrl(`assets/${plat}.png`)} alt={source} />}
    </div>
  );
}
const TS_PHOTOS = {
  "Gilad Water": "gilad-water",
  "Brett Foreman": "brett-foreman",
  "Jeremy Pitault": "jeremy-pitault",
  "Omer Malchim": "omer-malchim",
  "Anne Hay": "anne-hay",
  "Jon Sumroy": "jon-sumroy",
  "Christie Teller": "christie-teller",
  "Joseph Nguyen": "joseph-nguyen",
};
function TsAvatar({ t }) {
  const initials = t.name.split(/\s+/).map((w) => w[0]).slice(0, 2).join("").toUpperCase();
  const slug = TS_PHOTOS[t.name];
  return (
    <div className="ts-avatar" style={t.tone ? { background: t.tone } : undefined}>
      {slug ? <img src={rasterAsset(`assets/headshots/${slug}`)} alt={t.name} /> : initials}
    </div>
  );
}
function TsCard({ t, w }) {
  return (
    <div className="tsx-card card-mat" style={w ? { flex: `0 0 ${w}px`, width: w + "px" } : undefined}>
      <div className="tsx-top">
        <div className={"tsx-logo" + (t.tallLogo ? " tsx-logo--tall" : "") + (t.bigLogo ? " tsx-logo--big" : "")}>
          {t.logo ? <img src={rasterAsset(`assets/clients/${t.logo}`)} alt={t.company} /> : <span className="tsx-logo-txt">{t.company}</span>}
        </div>
        <TsRating source={t.src} />
      </div>
      <div className="ts-hl">{t.hl}</div>
      <p className="ts-quote">{"\u201C" + t.quote + "\u201D"}</p>
      <div className="ts-tags">{t.tags.map((x) => <span className="tool-chip" key={x}>{x}</span>)}</div>
      <div className="tsx-divider" />
      <div className="tsx-person">
        <TsAvatar t={t} />
        <div className="tsx-line">
          <span className="tsx-name">{t.name}</span>
          <span className="tsx-dotsep">&middot;</span>
          <span className="tsx-role">{t.role}</span>
          {t.company && t.company !== t.name && <React.Fragment>
            <span className="tsx-dotsep">&middot;</span>
            <span className="tsx-co">{t.company}</span>
          </React.Fragment>}
        </div>
      </div>
    </div>
  );
}

function Testimonials() {
  const T = [
    { src: "", hl: "A complete Shopify CRO overhaul",
      quote: "Taurist took our Shopify store to the next level \u2014 modernizing the design, upgrading to Shopify 2.0, and dramatically improving how well our site converts. The difference was clear from day one.",
      name: "Jon Sumroy", role: "CEO, Founder & Inventor", company: "mifold", logo: "mifold", bigLogo: true,
      tags: ["Shopify 2.0", "CRO overhaul", "Ecommerce"] },
    { src: "", hl: "A thoughtful audit with tracking and funnel analysis",
      quote: "One of the most thorough, thoughtful, and insightful audits I have received on our website and business. The suggested plan made the path to better conversion feel clear.",
      name: "Joseph Nguyen", role: "NYT Best Seller", company: "Joseph Nguyen", logo: "josephnguyen", tone: "linear-gradient(140deg,#8C6BF0,#2A6FDB)",
      tags: ["CRO audit", "Funnel analysis", "Tracking"] },
    { src: "", hl: "A thorough Shopify optimization report",
      quote: "Conversion Works by Taurist provided an excellent report of site optimization opportunities. It was thorough, quick, and exactly the kind of support we would hire again. Edu is a pleasure to work with.",
      name: "Christie Teller", role: "Owner", company: "Tools for Wellness", logo: "toolsforwellness", tone: "linear-gradient(140deg,#1F8A5B,#2A6FDB)",
      tags: ["Shopify CRO", "Site audit", "Quick turnaround"] },
    { src: "", hl: "A go-to CRO and UX partner",
      quote: "I have worked with Taurist across client audits, eCommerce optimization, IA design, and site builds \u2014 and they always deliver. They bring sharp thinking, clean execution, and real CRO results.",
      name: "Omer Malchim", role: "Founder", company: "Moxie Method", logo: "moxiemethod", tone: "linear-gradient(140deg,#F22248,#8C6BF0)",
      tags: ["Audits", "Ecommerce optimization", "IA design"] },
    { src: "", hl: "Fast, focused, and results-driven",
      quote: "Conversion Works redesigned our website to better capture leads and reflect the speed of our business. They moved fast, stayed on budget, and consistently brought CRO thinking to the table. Their work also helped several of our DTC brands improve conversions on Shopify.",
      name: "Gilad Water", role: "Co-Founder", company: "Enso Brands", logo: "enso",
      tags: ["DTC brands", "Shopify conversion", "CRO thinking"] },
    { src: "", hl: "A secret weapon for growth",
      quote: "Conversion Works has been instrumental in helping us design and optimize countless websites over the last two years. Their conversion-focused design work has directly contributed to our growth. They just get it.",
      name: "Brett Foreman", role: "Founder", company: "CRO Pros", logo: "cropros", tone: "linear-gradient(140deg,#2A6FDB,#1F8A5B)",
      tags: ["Conversion design", "Optimization", "Growth"] },
    { src: "", hl: "Several Shopify sites, always delivered",
      quote: "We've worked with Taurist on several Shopify sites and they've always delivered. They designed the Shinobi Japanese learning app and helped us roll out multiple high-converting eComm sites with speed and polish.",
      name: "Jeremy Pitault", role: "Founder", company: "Shinobi", logo: "shinobi", tone: "linear-gradient(140deg,#8C6BF0,#F22248)",
      tags: ["Shopify sites", "High-converting", "App design"] },
    { src: "", hl: "Clarity and focus for a complex site",
      quote: "Taurist brought clarity and focus to a very complex site with multiple product offerings. They restructured our homepage and navigation in a way that increased engagement and helped us onboard more clients faster. The impact was immediate and measurable.",
      name: "Anne Hay", role: "Marketing Leader", company: "PayNearMe", logo: "paynearme", tone: "linear-gradient(140deg,#2A6FDB,#8C6BF0)",
      tags: ["IA & navigation", "Engagement", "Onboarding"] },
  ];
  const N = T.length;
  const GAP = 20;
  const vpRef = useRef(null);
  const [step, setStep] = useState(0);
  const [cardw, setCardw] = useState(0);
  const [idx, setIdx] = useState(0);
  const [anim, setAnim] = useState(true);
  const paused = useRef(false);
  const headRef = useReveal();
  const wallRef = useReveal({ threshold: 0.05 });
  const ctaRef = useReveal();
  const secRef = useReveal({ threshold: 0, rootMargin: "0px 0px 0px 0px" });

  useEffect(() => {
    const measure = () => {
      const w = vpRef.current ? vpRef.current.clientWidth : 0;
      let d = 3.3, gaps = 3;
      if (w < 760) { d = 1.15; gaps = 1; }
      else if (w < 1100) { d = 2.2; gaps = 2; }
      const cw = Math.max(0, (w - GAP * gaps) / d);
      setCardw(cw); setStep(cw + GAP);
    };
    measure();
    window.addEventListener("resize", measure);
    return () => window.removeEventListener("resize", measure);
  }, []);

  useEffect(() => {
    const t = setInterval(() => { if (!paused.current) setIdx((i) => i + 1); }, 5000);
    return () => clearInterval(t);
  }, []);

  useEffect(() => {
    if (idx === N) {
      const t = setTimeout(() => { setAnim(false); setIdx(0); }, 640);
      return () => clearTimeout(t);
    }
    if (!anim) {
      const r = requestAnimationFrame(() => requestAnimationFrame(() => setAnim(true)));
      return () => cancelAnimationFrame(r);
    }
  }, [idx, anim]);

  const cards = [...T, ...T];

  const next = () => setIdx((i) => i + 1);
  const prev = () => setIdx((i) => {
    if (i <= 0) {
      setAnim(false);
      requestAnimationFrame(() => requestAnimationFrame(() => { setAnim(true); setIdx(N - 1); }));
      return N;
    }
    return i - 1;
  });

  return (
    <section id="proof" ref={secRef} className="section ts-sec">
      <div className="ts-streak-bg" aria-hidden="true" />
      <div className="haze-bloom" style={{ opacity: 0.14 }} aria-hidden="true" />
      <div className="wrap" style={{ position: "relative", zIndex: 1 }}>
        <div ref={headRef} className="reveal ts-head">
          <div>
            <div className="eyebrow"><span className="dot" />Testimonials</div>
            <h2 className="h-section" style={{ maxWidth: 640 }}>
              Clients trust the work because <span className="gradient-text">the roadmap holds up.</span>
            </h2>
            <p className="p-lead">
              From Shopify audits and funnel analysis to ecommerce optimization, IA, design, and test setup, the goal is always the same: find the real friction and give teams a plan they can confidently ship.
            </p>
          </div>
          <div className="ts-badges">
            <span className="pay-badge pay-badge--violet"><i className="ri-star-fill" />5-star reviewed</span>
            <span className="pay-badge pay-badge--violet"><i className="ri-shopping-bag-3-line" />Shopify + CRO work</span>
            <span className="pay-badge pay-badge--violet"><i className="ri-verified-badge-line" />Upwork verified</span>
            <span className="pay-badge pay-badge--violet"><i className="ri-team-line" />Taurist clients</span>
            <span className="pay-badge pay-badge--violet"><i className="ri-award-line" />Clutch</span>
            <span className="pay-badge pay-badge--violet"><i className="ri-shield-star-line" />Trustpilot</span>
          </div>
        </div>

        <div ref={wallRef} className="ts-wall">
          <div className="tsx-viewport" ref={vpRef}
            onMouseEnter={() => { paused.current = true; }} onMouseLeave={() => { paused.current = false; }}>
            <div className="tsx-track" style={{ gap: GAP + "px", transform: `translateX(${-idx * step}px)`, transition: anim ? "transform .6s var(--ease)" : "none" }}>
              {cards.map((t, i) => <TsCard key={i} t={t} w={cardw} />)}
            </div>
          </div>
          <div className="tsx-controls">
            <div className="tsx-dots">
              {T.map((_, i) => (
                <button key={i} className={"tsx-dot" + ((idx % N) === i ? " on" : "")} onClick={() => setIdx(i)} aria-label={"Go to testimonial " + (i + 1)} />
              ))}
            </div>
            <div className="tsx-arrows">
              <button className="tsx-arrow" onClick={prev} aria-label="Previous testimonial"><i className="ri-arrow-left-s-line" /></button>
              <button className="tsx-arrow" onClick={next} aria-label="Next testimonial"><i className="ri-arrow-right-s-line" /></button>
            </div>
          </div>
        </div>

        <div ref={ctaRef} className="reveal sw-foot-cta">
          <h3 className="sw-foot-h">Want to see what your <span className="gradient-text">audit would find?</span></h3>
          <div className="sw-foot-actions">
            <a href="#cta" className="btn btn-primary">Book a Shopify audit consult <i className="ri-arrow-right-line" /></a>
            <a href="#cta" className="btn btn-secondary">Get 5 free fixes</a>
          </div>
        </div>
      </div>
    </section>
  );
}
Object.assign(window, { Testimonials });
