// Testimonials — trust badges + asymmetric card mosaic

const TRUST_BADGES = [
  { score: "4.9", platform: "G2",           meta: "230+ reviews" },
  { score: "5.0", platform: "Capterra",     meta: "180+ reviews" },
  { score: "#1",  platform: "Product Hunt", meta: "AI Agents"    },
];

const TESTIMONIALS = {
  left: [
    {
      quote: "From a rough brief to a deployed product in six weeks. Genuinely the best outside team we've worked with.",
      name: "Elena Russo",
      role: "CEO, Meridian AI",
      avatar: "assets/reviews/testimonials-1.jpg",
    },
    {
      quote: "They bring opinions, push back when it matters, and ship clean code every sprint without exception.",
      name: "Alex Park",
      role: "CTO, Forma Labs",
      avatar: "assets/reviews/testimonials-2.jpg",
    },
    {
      quote: "Weekly updates were sharp, decisions were fast, and every sprint shipped measurable progress.",
      name: "Priya Nair",
      role: "Head of Product, Northbay",
      avatar: "assets/reviews/testimonials-6.jpg",
    },
    {
      quote: "They translated a messy backlog into a clean roadmap and executed it without churn.",
      name: "Daniel Costa",
      role: "Founder, Neuronix",
      avatar: "assets/reviews/testimonials-1.jpg",
    },
  ],
  featured: {
    quote: "We went from nothing to a production AI copilot in 7 weeks — design, evals, and infrastructure fully handled. Our team couldn't have done this in six months on our own.",
    name: "Marcus Obi",
    role: "VP Product",
    company: "Helix Systems",
    avatar: "assets/reviews/testimonials-5.jpg",
    video: "assets/reviews/testimonial featured video.mp4",
  },
  right: [
    {
      quote: "Eval-first engineering gave us real confidence before shipping. Latency under 300ms p95 from day one.",
      name: "Sara Kim",
      role: "Staff Engineer, Rayfield",
      avatar: "assets/reviews/testimonials-3.jpg",
    },
    {
      quote: "The hand-off was the cleanest I've seen — CI, evals, and docs all ready. Zero ramp-up for our engineers.",
      name: "Julien Moreau",
      role: "CPO, Stackfield",
      avatar: "assets/reviews/testimonials-4.jpg",
    },
    {
      quote: "Performance targets were met in the first release and stayed stable as traffic scaled.",
      name: "Mina Lee",
      role: "Engineering Manager, Arclytics",
      avatar: "assets/reviews/testimonials-3.jpg",
    },
    {
      quote: "They balanced speed with quality better than any team we've partnered with to date.",
      name: "Omar Haddad",
      role: "COO, Kestrel Cloud",
      avatar: "assets/reviews/testimonials-5.jpg",
    },
  ],
};

const MORE_REVIEWS = [
  {
    quote: "Scope was locked tight and they held it the entire engagement. Not a single missed milestone across eight weeks.",
    name: "Cleo Davis",
    role: "Product Lead, Caspian",
    avatar: "assets/reviews/testimonials-6.jpg",
  },
  {
    quote: "Our internal team learned more from watching them work than from any training we'd run. Genuinely senior-level pairing.",
    name: "Tom Whitfield",
    role: "Head of AI, Luminos",
    avatar: "assets/reviews/testimonials-1.jpg",
  },
  {
    quote: "We cut support tickets by 31% in the first month post-launch. The quality of the UX work was the differentiator.",
    name: "Nadia Osei",
    role: "VP Customer Success, Orbis",
    avatar: "assets/reviews/testimonials-2.jpg",
  },
  {
    quote: "The eval harness they shipped has become the single most valuable artifact from the engagement. We still run it daily.",
    name: "Riku Tanaka",
    role: "ML Lead, Threadline",
    avatar: "assets/reviews/testimonials-3.jpg",
  },
  {
    quote: "Three agencies told us it couldn't be done in under three months. Aigocy shipped it in seven weeks.",
    name: "Amara Diallo",
    role: "COO, Veridian",
    avatar: "assets/reviews/testimonials-4.jpg",
  },
  {
    quote: "Security review, RBAC, SSO — all handled without a single back-and-forth. They anticipated every enterprise requirement.",
    name: "Felix Krause",
    role: "CISO, Stackform",
    avatar: "assets/reviews/testimonials-5.jpg",
  },
];

// ─── Stars ────────────────────────────────────────────────────
const Stars = ({ count = 5, size = 13 }) => (
  <div className="ag-stars" role="img" aria-label={`${count} out of 5 stars`}>
    {Array.from({ length: 5 }, (_, i) => (
      <svg
        key={i}
        width={size} height={size}
        viewBox="0 0 16 16"
        aria-hidden="true"
        className={"ag-star" + (i < count ? " is-filled" : "")}
      >
        <polygon points="8,1 10,5.5 15,6 11,9.5 12.5,14.5 8,12 3.5,14.5 5,9.5 1,6 6,5.5"/>
      </svg>
    ))}
  </div>
);

// ─── TrustBadge ───────────────────────────────────────────────
const TrustBadge = ({ score, platform, meta }) => (
  <div className="ag-trust-badge">
    <span className="ag-trust-badge__score">{score}</span>
    <span className="ag-trust-badge__sep" aria-hidden="true"/>
    <div>
      <Stars count={5} size={11} />
      <div className="ag-trust-badge__meta">{platform} · {meta}</div>
    </div>
  </div>
);

// ─── TestimonialCard ──────────────────────────────────────────
const TestimonialCard = ({ quote, name, role, avatar }) => (
  <article className="ag-tcard">
    <p className="ag-tcard__quote">"{quote}"</p>
    <footer className="ag-tcard__footer">
      <span
        className="ag-avatar"
        style={{ backgroundImage: `url('${avatar}')` }}
        role="img"
        aria-label={name}
      />
      <div>
        <div className="ag-about__quoter-name">{name}</div>
        <div className="ag-about__quoter-role">{role}</div>
      </div>
    </footer>
  </article>
);

// ─── FeaturedVideo — interactive video area ───────────────────
const FeaturedVideo = ({ src, lang }) => {
  const videoRef = React.useRef(null);
  const [playing, setPlaying] = React.useState(false);

  const toggle = (e) => {
    e.stopPropagation();
    const v = videoRef.current;
    if (!v) return;
    if (playing) { v.pause(); } else { v.play(); }
    setPlaying(!playing);
  };

  return (
    <div className="ag-tfeatured__media">
      <video
        ref={videoRef}
        src={src}
        playsInline
        loop
        className="ag-tfeatured__video"
        onEnded={() => setPlaying(false)}
      />
      <div className="ag-tfeatured__media-overlay">
        <span className="ag-tfeatured__media-tag">
          <span className="ag-chip ag-chip--dark">
            <SparkleIcon size={11} />
            {t('testimonials.featured', lang)}
          </span>
        </span>
        <button
          className="ag-card-video__btn"
          onClick={toggle}
          type="button"
          aria-label={playing ? "Pause" : "Play"}
        >
          {playing ? (
            <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor">
              <rect x="5" y="4" width="4" height="16" rx="1"/>
              <rect x="15" y="4" width="4" height="16" rx="1"/>
            </svg>
          ) : (
            <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
              <polygon points="7,3 21,12 7,21"/>
            </svg>
          )}
        </button>
      </div>
    </div>
  );
};

// ─── FeaturedTestimonialCard ──────────────────────────────────
const FeaturedTestimonialCard = ({ quote, name, role, company, avatar, video, lang }) => (
  <article className="ag-tfeatured">
    <div className="ag-tfeatured__body">
      <Stars count={5} size={14} />
      <p className="ag-tfeatured__quote">"{quote}"</p>
      <footer className="ag-tfeatured__footer">
        <div className="ag-reviews__reviewer">
          <span
            className="ag-avatar"
            style={{ backgroundImage: `url('${avatar}')` }}
            role="img"
            aria-label={name}
          />
          <div>
            <div className="ag-about__quoter-name">{name}</div>
            <div className="ag-about__quoter-role">{role} · {company}</div>
          </div>
        </div>
        <a href="#" className="ag-tcard-link">
          {t('testimonials.readMore', lang)}
          <ChevronRight />
        </a>
      </footer>
    </div>
    <FeaturedVideo src={video} lang={lang} />
  </article>
);

// ─── Testimonials ─────────────────────────────────────────────
const Testimonials = ({ data, lang }) => {
  // Map CMS reviews array into layout columns, or fall back to static data
  let tLeft, tFeatured, tRight, tMore;
  const hasSection = data !== null && data !== undefined;
  if (hasSection) {
    const all = Array.isArray(data) ? [...data].sort((a, b) => (a.order ?? 0) - (b.order ?? 0)).map(r => ({
      quote:   i18(r.quote, lang)   || '',
      name:    r.name               || '',
      role:    i18(r.role, lang)    || '',
      company: i18(r.company, lang) || '',
      avatar:  r.avatar       || '',
      video:   r.video        || '',
      featured: r.featured    || false,
    })) : [];
    tFeatured = all.find(r => r.featured) || all[0] || null;
    const nonFeatured = all.filter(r => !r.featured);
    tLeft  = nonFeatured.filter((_, i) => i % 2 === 0).slice(0, 4);
    tRight = nonFeatured.filter((_, i) => i % 2 === 1).slice(0, 4);
    tMore  = nonFeatured.slice(8);
  } else {
    tFeatured = TESTIMONIALS.featured;
    tLeft     = TESTIMONIALS.left;
    tRight    = TESTIMONIALS.right;
    tMore     = MORE_REVIEWS;
  }

  const [expanded, setExpanded] = React.useState(false);

  return (
    <section className="ag-testimonials" id="ag-section-reviews">
      <div className="ag-testimonials__trust" role="list" aria-label="Review platform ratings">
        {TRUST_BADGES.map((b) => (
          <div key={b.platform} role="listitem">
            <TrustBadge {...b} />
          </div>
        ))}
      </div>

      <SectionHeading
        eyebrow={t('testimonials.eyebrow', lang)}
        sub={t('testimonials.sub', lang)}
      >
        {t('testimonials.heading1', lang)}<br/>{t('testimonials.heading2', lang)}
      </SectionHeading>

      <div className="ag-testimonials__grid" role="list">
        <div className="ag-testimonials__col ag-testimonials__col--left" role="presentation">
          {tLeft.map((t) => (
            <div key={t.name} role="listitem">
              <TestimonialCard {...t} />
            </div>
          ))}
          {expanded && tMore.slice(0, 2).map((t) => (
            <div key={t.name} role="listitem">
              <TestimonialCard {...t} />
            </div>
          ))}
        </div>

        <div className="ag-testimonials__col ag-testimonials__col--center" role="listitem">
          {tFeatured && <FeaturedTestimonialCard {...tFeatured} lang={lang} />}
          {expanded && tMore.slice(2, 4).map((t) => (
            <div key={t.name} role="listitem">
              <TestimonialCard {...t} />
            </div>
          ))}
        </div>

        <div className="ag-testimonials__col ag-testimonials__col--right" role="presentation">
          {tRight.map((t) => (
            <div key={t.name} role="listitem">
              <TestimonialCard {...t} />
            </div>
          ))}
          {expanded && tMore.slice(4).map((t) => (
            <div key={t.name} role="listitem">
              <TestimonialCard {...t} />
            </div>
          ))}
        </div>
      </div>

      <div className="ag-testimonials__cta">
        <button
          className="ag-tcard-link ag-tcard-link--lg"
          onClick={() => setExpanded(!expanded)}
          type="button"
        >
          {t(expanded ? 'testimonials.showLess' : 'testimonials.showMore', lang)}
          <ChevronRight style={{ transform: expanded ? "rotate(270deg)" : "rotate(90deg)", transition: "transform 200ms ease" }} />
        </button>
      </div>
    </section>
  );
};

window.Testimonials = Testimonials;
