/* Featured testimonials + full testimonials page.

   <TestimonialsFeatured />  On each page load, picks 1 video + 2 written quotes
                             at random from the items marked `featured: true`
                             in TESTIMONIAL_ITEMS (src/Testimonials.jsx), with a
                             "See all testimonials" link. Same props as
                             <Testimonials />, so it can replace it 1:1.

   <TestimonialsAll />       Everything in TESTIMONIAL_ITEMS for Testimonials.html:
                             a video player, then a rotating quote card,
                             each with arrows and a position counter.

   TO FEATURE A TESTIMONIAL: add `featured: true` to it in src/Testimonials.jsx.
   Keep at least 1 featured video and 2 featured written quotes.

   Load src/Testimonials.jsx before this file. */

const ALL_TESTIMONIALS_HREF = "/testimonials";

const pickRandom = (arr, n) => {
  const a = arr.slice();
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a.slice(0, n);
};

/* ── Featured row (for the homepage, Club, Accelerator, UCB) ──────────── */
const TestimonialsFeatured = ({
  num = "05",
  eyebrow = "In their words",
  heading = "What clients say after the work.",
  screenLabel = "05 Testimonials",
  bg = "var(--paper)",
  excludeNames = [],   // names to leave out of this page's featured rotation
} = {}) => {
  const [openQuote, setOpenQuote] = React.useState(null);
  const picks = React.useMemo(() => {
    const feat = TESTIMONIAL_ITEMS.filter((t) => t.featured && !excludeNames.includes(t.name));
    const vids = feat.filter((t) => t.type === "video");
    const quotes = feat.filter((t) => t.type === "quote");
    return { video: pickRandom(vids, 1)[0], quotes: pickRandom(quotes, 2) };
  }, []);

  return (
    <section id="testimonials" data-screen-label={screenLabel} style={{ background: bg }}>
      <div className="wrap">
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 24, flexWrap: "wrap", marginBottom: 40 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 24 }}>
              <span className="num">{num}</span> {eyebrow}
            </div>
            <h2 className="h2" style={{ maxWidth: "20ch" }}>{heading}</h2>
          </div>
          <a href={ALL_TESTIMONIALS_HREF} className="ulink" style={{ fontSize: 15, fontWeight: 600, color: "var(--ink)", whiteSpace: "nowrap" }}>
            See all testimonials →
          </a>
        </div>

        <div className="tf-row">
          {picks.video && <TVideoCard v={picks.video} />}
          {picks.quotes.map((q, i) => <TQuoteCard key={i} q={q} onOpen={() => setOpenQuote(q)} />)}
        </div>
      </div>

      {openQuote && <TQuoteModal q={openQuote} onClose={() => setOpenQuote(null)} />}
      <TCardStyles />
      <style>{`
        .tf-row { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 20px; align-items: stretch; }
        @media (max-width: 900px) { .tf-row { grid-template-columns: 1fr; max-width: 560px; } }
      `}</style>
    </section>
  );
};

/* Random starting position: pick one of the featured items (like the section
   rotators), so visitors don't always land on the same person. */
const randomFeaturedStart = (list) => {
  const feat = list.map((t, i) => (t.featured ? i : -1)).filter((i) => i >= 0);
  const pool = feat.length ? feat : list.map((_, i) => i);
  return pool.length ? pool[Math.floor(Math.random() * pool.length)] : 0;
};

/* Best available YouTube thumbnail. maxresdefault doesn't exist for every
   video: YouTube answers 404 with a small gray placeholder image that would
   cover the fallback, so check the real size before using it. */
const useBestThumb = (v) => {
  const [url, setUrl] = React.useState(null);
  React.useEffect(() => {
    if (!v) return;
    if (v.thumb) { setUrl(v.thumb); return; }
    let dead = false;
    const base = `https://i.ytimg.com/vi/${v.id}/`;
    setUrl(base + "hqdefault.jpg");
    const tryNext = (names) => {
      if (!names.length) return;
      const img = new Image();
      img.onload = () => { if (!dead && img.naturalWidth > 200) setUrl(base + names[0]); else if (!dead) tryNext(names.slice(1)); };
      img.onerror = () => { if (!dead) tryNext(names.slice(1)); };
      img.src = base + names[0];
    };
    tryNext(["maxresdefault.jpg", "sddefault.jpg"]);
    return () => { dead = true; };
  }, [v && v.id]);
  return url;
};

/* ── Full page (for Testimonials.html) ────────────────────────────────
   Two showcases with the same layout: a video player, then a quote card.
   Each has arrows and a position counter (e.g. Video 03 / 08). Both grow with TESTIMONIAL_ITEMS without getting taller. */
const TestimonialsAll = () => (
  <React.Fragment>
    <section data-screen-label="01 Testimonials" style={{ paddingTop: 88, paddingBottom: 48 }}>
      <div className="wrap">
        <div className="eyebrow" style={{ marginBottom: 28 }}>
          <span className="num">01</span> In their words
        </div>
        <h1 className="display" style={{ maxWidth: "14ch", marginBottom: 24 }}>What clients say after the work.</h1>
        <p className="lede" style={{ maxWidth: "48ch" }}>
          Real people, real career changes. Hear it from them.
        </p>
      </div>
    </section>
    <VideoShowcase />
    <QuoteShowcase />
  </React.Fragment>
);

/* Big player + playlist */
const VideoShowcase = () => {
  const vids = TESTIMONIAL_ITEMS.filter((t) => t.type === "video");
  const [idx, setIdx] = React.useState(() => randomFeaturedStart(vids));
  const [playing, setPlaying] = React.useState(false);
  const go = (i) => { setIdx((i + vids.length) % vids.length); setPlaying(false); };
  const v = vids[idx];
  const thumb = useBestThumb(v);
  if (!v) return null;
  return (
    <section data-screen-label="02 Watch" style={{ background: "var(--paper)" }}>
      <div className="wrap">
        <div className="vs-grid">
          <div className="eyebrow" style={{ marginBottom: 28 }}>
            <span className="num">02</span> Watch
          </div>
          <div>
            <div style={{ aspectRatio: "16 / 9", position: "relative", borderRadius: 14, overflow: "hidden", background: "var(--ink)", boxShadow: "0 24px 60px rgba(10, 31, 61, 0.14)" }}>
              {playing
                ? <iframe key={v.id}
                    src={`https://www.youtube-nocookie.com/embed/${v.id}?autoplay=1&rel=0`}
                    title={v.name}
                    referrerPolicy="strict-origin-when-cross-origin"
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                    allowFullScreen
                    style={{ width: "100%", height: "100%", border: 0, display: "block" }} />
                : <button onClick={() => setPlaying(true)} aria-label={`Play ${v.name}'s testimonial`} style={{
                    position: "absolute", inset: 0, padding: 0, border: 0, cursor: "pointer",
                    background: `center / cover no-repeat url(${thumb || `https://i.ytimg.com/vi/${v.id}/hqdefault.jpg`}), var(--ink)`,
                    display: "flex", alignItems: "center", justifyContent: "center",
                  }}>
                    <span style={{
                      width: 76, height: 76, borderRadius: "50%", background: "var(--accent)", color: "#fff",
                      display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 8px 26px rgba(0,0,0,0.35)",
                    }}>
                      <svg width="30" height="30" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
                    </span>
                  </button>}
            </div>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 20, marginTop: 22, flexWrap: "wrap" }}>
              <div>
                <div style={{ fontWeight: 600, fontSize: 24, color: "var(--ink)", letterSpacing: "-0.02em" }}>{v.name}</div>
                <div className="meta" style={{ marginTop: 6 }}>{v.role}</div>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                <span className="meta" style={{ color: "var(--ink-dim)" }}>
                  Video {String(idx + 1).padStart(2, "0")} / {String(vids.length).padStart(2, "0")}
                </span>
                <RoundArrow dir="left" onClick={() => go(idx - 1)} />
                <RoundArrow dir="right" onClick={() => go(idx + 1)} />
              </div>
            </div>
          </div>

        </div>
      </div>
      <style>{`
        .vs-grid { max-width: 880px; margin: 0 auto; }
      `}</style>
    </section>
  );
};

/* Written: quote card + list of people, mirroring the video section */
const QuoteShowcase = () => {
  const quotes = TESTIMONIAL_ITEMS.filter((t) => t.type === "quote");
  const [idx, setIdx] = React.useState(() => randomFeaturedStart(quotes));
  const [paused, setPaused] = React.useState(false);
  const go = (i) => setIdx((i + quotes.length) % quotes.length);
  React.useEffect(() => {
    if (paused || quotes.length < 2) return;
    const id = setInterval(() => setIdx((i) => (i + 1) % quotes.length), 12000);
    return () => clearInterval(id);
  }, [paused, quotes.length]);
  const q = quotes[idx];
  if (!q) return null;
  const long = q.quote.length > 450;
  return (
    <section data-screen-label="03 Read" style={{ background: "var(--bg)" }}
      onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>
      <div className="wrap">
        <div className="vs-grid">
          <div className="eyebrow" style={{ marginBottom: 28 }}>
            <span className="num">03</span> Read
          </div>
          <div>
            <article style={{
              background: "var(--paper)", border: "1px solid var(--rule)", borderLeft: "3px solid var(--accent)",
              borderRadius: 14, padding: "40px 48px", aspectRatio: "16 / 9", display: "flex", flexDirection: "column",
              justifyContent: "center", overflow: "hidden", boxShadow: "0 24px 60px rgba(10, 31, 61, 0.08)",
            }} className="qs-card">
              <p key={idx} className="qs-fade" style={{
                margin: 0, color: "var(--ink)", letterSpacing: "-0.005em",
                fontSize: long ? "clamp(16px, 1.45vw, 19px)" : "clamp(19px, 1.9vw, 24px)", lineHeight: 1.6,
              }}>
                <span style={{ color: "var(--accent)", fontWeight: 600 }}>“</span>{q.quote}<span style={{ color: "var(--accent)", fontWeight: 600 }}>”</span>
              </p>
            </article>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 20, marginTop: 22, flexWrap: "wrap" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                <QsAvatar q={q} size={48} />
                <div>
                  <div style={{ fontWeight: 600, fontSize: 20, color: "var(--ink)", letterSpacing: "-0.015em" }}>{q.name}</div>
                  <div className="meta" style={{ marginTop: 4 }}>{q.role}</div>
                </div>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
                <span className="meta" style={{ color: "var(--ink-dim)" }}>
                  Written {String(idx + 1).padStart(2, "0")} / {String(quotes.length).padStart(2, "0")}
                </span>
                <RoundArrow dir="left" onClick={() => go(idx - 1)} />
                <RoundArrow dir="right" onClick={() => go(idx + 1)} />
              </div>
            </div>
          </div>

        </div>
      </div>
      <style>{`
        @keyframes qsFade { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
        .qs-fade { animation: qsFade 450ms ease both; }
        .qs-card .qs-fade { }
        @media (max-width: 980px) { .qs-card { aspect-ratio: auto !important; padding: 28px 26px !important; } }
      `}</style>
    </section>
  );
};

const QsAvatar = ({ q, size }) => q.photo
  ? <img src={q.photo} alt="" style={{ width: size, height: size, borderRadius: "50%", objectFit: "cover", border: "1px solid var(--rule)", flexShrink: 0 }} />
  : <span style={{
      width: size, height: size, borderRadius: "50%", flexShrink: 0,
      background: "var(--ink)", color: "var(--bg)", border: "2px solid var(--accent)",
      display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 500,
      fontSize: q.name === "Anonymous" ? size * 0.42 : size * 0.32,
    }}>{q.name === "Anonymous" ? "❝" : q.name.split(" ").map((s) => s[0]).filter(Boolean).slice(0, 2).join("")}</span>;

const RoundArrow = ({ dir, onClick, onInk }) => (
  <button onClick={onClick} aria-label={dir === "left" ? "Previous" : "Next"} style={{
    width: 44, height: 44, borderRadius: "50%", cursor: "pointer",
    background: onInk ? "transparent" : "var(--bg)",
    border: onInk ? "1px solid rgba(255,255,255,0.25)" : "1px solid var(--rule)",
    color: onInk ? "var(--on-ink)" : "var(--ink)",
    display: "flex", alignItems: "center", justifyContent: "center",
  }}>
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
      {dir === "left" ? <polyline points="15 18 9 12 15 6" /> : <polyline points="9 18 15 12 9 6" />}
    </svg>
  </button>
);

/* ── Shared card styles ───────────────────────────────────────────────── */
const TCardStyles = () => (
  <style>{`
    .t-card2 {
      background: var(--bg); border: 1px solid var(--rule); border-left: 3px solid var(--accent);
      border-radius: 12px; display: flex; flex-direction: column; overflow: hidden; height: 100%;
    }
    .t-clamp { display: -webkit-box; -webkit-line-clamp: 7; -webkit-box-orient: vertical; overflow: hidden; }
  `}</style>
);

/* ── Video card: thumbnail plays in place ─────────────────────────────── */
const TVideoCard = ({ v, compact }) => {
  const [playing, setPlaying] = React.useState(false);
  const thumb = v.thumb || `https://i.ytimg.com/vi/${v.id}/mqdefault.jpg`;
  return (
    <article className="t-card2">
      <div style={{ aspectRatio: "16 / 9", position: "relative", background: "var(--ink)", flexShrink: 0 }}>
        {playing
          ? <iframe
              src={`https://www.youtube-nocookie.com/embed/${v.id}?autoplay=1&rel=0`}
              title={v.name}
              referrerPolicy="strict-origin-when-cross-origin"
              allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
              allowFullScreen
              style={{ width: "100%", height: "100%", border: 0, display: "block" }}
            />
          : <button onClick={() => setPlaying(true)} aria-label={`Play ${v.name}'s testimonial`} style={{
              position: "absolute", inset: 0, padding: 0, border: 0, cursor: "pointer",
              background: `center / cover no-repeat url(${thumb}), var(--ink)`,
              display: "flex", alignItems: "center", justifyContent: "center",
            }}>
              <span style={{
                width: compact ? 46 : 56, height: compact ? 46 : 56, borderRadius: "50%", background: "var(--accent)", color: "#fff",
                display: "flex", alignItems: "center", justifyContent: "center", boxShadow: "0 6px 18px rgba(0,0,0,0.3)",
              }}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
              </span>
            </button>}
      </div>
      <div style={{ padding: compact ? "16px 18px 18px" : "22px 24px", display: "flex", flexDirection: "column", flex: 1 }}>
        {!compact && <div className="meta" style={{ color: "var(--accent-deep)", marginBottom: 10 }}>Video testimonial</div>}
        <div style={{ fontWeight: 600, fontSize: compact ? 16 : 18, color: "var(--ink)", letterSpacing: "-0.015em" }}>{v.name}</div>
        <div className="meta" style={{ marginTop: 4 }}>{v.role}</div>
        {!playing && !compact && (
          <button onClick={() => setPlaying(true)} style={{
            marginTop: "auto", paddingTop: 18, alignSelf: "flex-start", border: 0, background: "none", paddingLeft: 0,
            fontFamily: "var(--sans)", fontSize: 14, fontWeight: 600, color: "var(--ink)", cursor: "pointer",
          }}>Watch →</button>
        )}
      </div>
    </article>
  );
};

/* ── Written card: clamped, "Read more" opens the full quote ─────────── */
const TQuoteCard = ({ q, onOpen }) => {
  const long = q.quote.length > 260;
  return (
    <article className="t-card2" style={{ padding: "26px 24px 22px" }}>
      <p className={long ? "t-clamp" : ""} style={{ margin: 0, fontSize: 15.5, lineHeight: 1.62, color: "var(--ink)" }}>
        <span style={{ color: "var(--accent)", fontWeight: 600 }}>“</span>{q.quote}<span style={{ color: "var(--accent)", fontWeight: 600 }}>”</span>
      </p>
      {long && (
        <button onClick={onOpen} style={{
          alignSelf: "flex-start", marginTop: 8, padding: 0, border: 0, background: "none",
          fontFamily: "var(--sans)", fontSize: 13.5, fontWeight: 600, color: "var(--accent-deep)", cursor: "pointer",
        }}>Read more</button>
      )}
      <div style={{ marginTop: "auto", paddingTop: 20 }}><TPerson q={q} /></div>
    </article>
  );
};

const TPerson = ({ q }) => {
  const initials = q.name === "Anonymous"
    ? "❝"
    : q.name.split(" ").map((s) => s[0]).filter(Boolean).slice(0, 2).join("");
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12, paddingTop: 16, borderTop: "1px solid var(--rule)" }}>
      {q.photo
        ? <img src={q.photo} alt="" style={{ width: 40, height: 40, borderRadius: "50%", objectFit: "cover", border: "1px solid var(--rule)", flexShrink: 0 }} />
        : <span style={{
            width: 40, height: 40, borderRadius: "50%", flexShrink: 0,
            background: "var(--ink)", color: "var(--bg)", border: "2px solid var(--accent)",
            display: "flex", alignItems: "center", justifyContent: "center",
            fontSize: q.name === "Anonymous" ? 18 : 13, fontWeight: 500,
          }}>{initials}</span>}
      <div style={{ minWidth: 0 }}>
        <div style={{ fontWeight: 600, fontSize: 15, color: "var(--ink)" }}>{q.name}</div>
        <div className="meta" style={{ marginTop: 2 }}>{q.role}</div>
      </div>
    </div>
  );
};

/* ── Full quote in an overlay ─────────────────────────────────────────── */
const TQuoteModal = ({ q, onClose }) => {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);
  return (
    <div onClick={onClose} style={{
      position: "fixed", inset: 0, zIndex: 100, background: "rgba(10, 31, 61, 0.55)",
      display: "flex", alignItems: "center", justifyContent: "center", padding: 20,
    }}>
      <div onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" style={{
        background: "var(--bg)", borderLeft: "3px solid var(--accent)", borderRadius: 14,
        maxWidth: 620, width: "100%", maxHeight: "85vh", overflowY: "auto", padding: "34px 34px 28px", position: "relative",
      }}>
        <button onClick={onClose} aria-label="Close" style={{
          position: "absolute", top: 12, right: 14, border: 0, background: "none",
          fontSize: 24, lineHeight: 1, color: "var(--ink-dim)", cursor: "pointer",
        }}>×</button>
        <p style={{ margin: "0 0 24px", fontSize: 17, lineHeight: 1.65, color: "var(--ink)" }}>
          <span style={{ color: "var(--accent)", fontWeight: 600 }}>“</span>{q.quote}<span style={{ color: "var(--accent)", fontWeight: 600 }}>”</span>
        </p>
        <TPerson q={q} />
      </div>
    </div>
  );
};

window.TestimonialsFeatured = TestimonialsFeatured;
window.TestimonialsAll = TestimonialsAll;
