// Testimonials.jsx — "Client proof" auto-advancing carousel.
// Shows ~3 cards + a faded 4th; advances every 5s, loops seamlessly, pauses on hover.
// Card: client logo (top-left) + stars (top-right), review title, 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 = {
  "Lucas Braga": "lucas-braga", "Gilad Water": "gilad-water", "Francine Demelo": "francine-demelo-face",
  "Louis Long": "louis-long", "Daivik Patel": "daivik-patel", "Tanner Luke": "tanner-luke",
  "Chantel Jeffers": "chantel-jeffers-face", "Julian Parr": "julian-parr", "Matthew Lee": "matthew-lee",
};
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={assetUrl(`assets/headshots/${slug}.png`)} 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.logo ? <img src={assetUrl(`assets/clients/${t.logo}.png`)} 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>
          <span className="tsx-dotsep">&middot;</span>
          <span className="tsx-co">{t.company}</span>
        </div>
      </div>
    </div>
  );
}

function Testimonials() {
  const T = [
    { src: "", hl: "Website, pages, and CRM working together",
      quote: "Taurist built our website, landing pages, and full HubSpot CRM — and made it all work together.",
      name: "Lucas Braga", role: "Co-Founder", company: "Braga Brothers", logo: "bragabrothers",
      tags: ["Website", "Landing pages", "CRM"] },
    { src: "Clutch", hl: "Built for signups, not just screens",
      quote: "Taurist helped us design a website and app experience that drove user signups.",
      name: "Louis Long", role: "Co-Founder", company: "Conquer App", logo: "conquer",
      tags: ["Website", "App UX", "Growth"] },
    { src: "", hl: "A site built to capture more demand",
      quote: "Taurist redesigned our website to better capture leads and reflect the speed of our business.",
      name: "Gilad Water", role: "Co-Founder", company: "Enso Brands", logo: "enso",
      tags: ["Website redesign", "Lead capture", "CRO"] },
    { src: "Trustpilot", hl: "Speed without sacrificing quality",
      quote: "They moved quickly without compromising design or conversion.",
      name: "Daivik Patel", role: "CEO & Co-Founder", company: "Aiirify", logo: "aiirify",
      tags: ["Website", "Landing pages", "Fast launch"] },
    { src: "Trustpilot", hl: "Above and beyond during the redesign",
      quote: "The Taurist team was extremely responsive and went above and beyond for our company.",
      name: "Matthew Lee", role: "Co-Founder / COO", company: "Conquer App", logo: "conquer",
      tags: ["Redesign", "UI/UX", "Founder support"] },
    { src: "Clutch", hl: "A long-term website partner",
      quote: "Taurist has been a trusted partner for over 5 years.",
      name: "Francine Demelo", role: "Founder", company: "Francine\u2019s Travel", logo: "francines",
      tags: ["Website", "Booking flow", "Custom tools"] },
    { src: "Trustpilot", hl: "Practical support for a local business",
      quote: "Communication and professional is excellent. Would definitely recommend.",
      name: "Chantel Jeffers", role: "Founder / CEO", company: "People Choice Movers", logo: "peoplechoice", tallLogo: true,
      tags: ["Local business", "Google profile", "Website support"] },
    { src: "Trustpilot", hl: "Design insight the team could trust",
      quote: "We not only got great design work, but also great insight.",
      name: "Tanner Luke", role: "Co-Founder", company: "Conquer App", logo: "conquer",
      tags: ["App design", "UX", "Product team"] },
    { src: "Trustpilot", hl: "Reliable UX and Webflow support",
      quote: "Their turnaround times, attention to detail and post-project support are all well above exemplary.",
      name: "Julian Parr", role: "Senior Marketing Manager", company: "Marble", logo: "marble",
      tags: ["UX", "Webflow", "Support"] },
  ];
  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 work holds up.</span>
            </h2>
            <p className="p-lead">
              From websites and landing pages to UX improvements, booking flows, CRM connections, and ongoing support, the goal is always the same: make the business easier to understand, trust, and choose.
            </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-team-line" />Taurist clients</span>
            <span className="pay-badge pay-badge--violet"><i className="ri-shield-star-line" />Trustpilot</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-briefcase-4-line" />Upwork</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">website could become?</span></h3>
          <div className="sw-foot-actions">
            <a href="#cta" className="btn btn-primary">Request my homepage prototype <i className="ri-arrow-right-line" /></a>
            <a href="#review" className="btn btn-secondary">See pricing</a>
          </div>
        </div>
      </div>
    </section>
  );
}
Object.assign(window, { Testimonials });
