/* Testimonials — unified rotator: written quotes + video testimonials in one loop.

   ──────────────────────────────────────────────────────────────────────────
   ADDING A TESTIMONIAL:

     Append an entry to the `TESTIMONIAL_ITEMS` array below. Two types:

     WRITTEN:
       {
         type: "quote",
         name:  "Sarah K.",
         role:  "VP Engineering · Tech",
         photo: "img/testimonials/sarah.png",   // optional — null for initials
         quote: "What they said.",
       }

     VIDEO (YouTube):
       {
         type:  "video",
         id:    "abc123",                        // YouTube video ID
         name:  "Sarah K.",
         role:  "VP Engineering · Tech",
         thumb: "img/testimonials/sarah-thumb.jpg",  // optional — YT default used otherwise
       }

   The rotator auto-cycles every 12s, pauses on hover, and pauses indefinitely
   while a video is playing. Order = display order; mix freely.
   ──────────────────────────────────────────────────────────────────────────
*/

const { useState, useEffect, useRef } = React;

const TESTIMONIAL_ITEMS = [
  {
    type: "video",
    id: "6KtUjm7j-GM",
    name: "Gabrielle Doran",
    role: "Data Science · Tech",
  },
  {
    type: "video",
    id: "K4CTB91uabw",
    name: "Yu Li",
    role: "Systems Engineering · Biotech",
  },
  {
    type: "video",
    id: "xWz6lyA65vc",
    name: "Sara Song",
    role: "Data Science · Tech",
  },
  {
    type: "quote",
    name: "Christine Siu",
    role: "VP of Product · Net Purpose",
    photo: "img/testimonials/christine-siu.png",
    quote: "I received coaching sessions from Hojeong and we worked through unpacking the tensions between my professional and personal lives. I found Hojeong to be adaptive in her coaching style and resourceful in her methods. She does just the right amount of push and pull, at times uncomfortable (remember, all growth experiences are!) and I always left with food for thought. One notable exercise we did was the visualisation of my future self. The sheer awareness gained over the one-hour session propelled me to launch my own business in a matter of weeks post, which has been growing strong since. Thank you, Hojeong! I highly recommend Hojeong's coaching.",
  },
  {
    type: "quote",
    name: "Giovanni Vazquez",
    role: "Director, Technical Program Management · nXu (EdTech)",
    photo: "img/testimonials/giovanni-vazquez.png",
    quote: "I had always suffered from simultaneously feeling like I wasn't really achieving my full potential, but never being able to put together a plan that I was confident in. It wasn't until I underwent a series of self-discovery and goal setting sessions with Hojeong that I was able to turn my self-doubt and imposter syndrome into self-actualization. I wholeheartedly believe it is what allowed me to take my ideas for process frameworks and my passion for building things to the next level. Not only did I find myself doing much better with work, I found that I was able to compartmentalize my personal life in a more meaningful, purposeful way. Rather than feeling like I'm spinning my wheels, I feel much more well-minded to do anything.",
  },
  {
    type: "quote",
    name: "Flor",
    role: "Operations Manager · Non-profit",
    photo: "img/testimonials/flor-saluzzo.png",
    quote: "Hojeong has been an absolute gift to have in my life. Our sessions are always insightful and full of introspection. The biggest impact she has had on me was on giving me back the confidence I had lost through bad experiences and impostor syndrome. Believing in my own capabilities and thoughts, understanding myself and feeling good about it rather than question it. They are not about reaching a career goal or a milestone, but rather being ok with who I really am now. She has also given me loads of practical career and life advices which I have followed to give me much more clarity.",
  },
  {
    type: "quote",
    name: "Ingrid O.",
    role: "Software Engineer · Tech",
    photo: null,
    quote: "I highly recommend Kim Coaching Group's Women Leaders Club! I found the sessions to be enlightening and thought-provoking, teaching useful self-reflection tools. It helped to clarify vision and purpose, and helped to find actionable paths to reaching my goal.",
  },
  {
    type: "quote",
    name: "Anonymous",
    role: "Senior leader · Tech",
    photo: null,
    quote: "I was impressed by the effectiveness of the session. Hojeong made me realize how attainable my goals are. They are no longer just in my imagination. I am extremely grateful for her authentic and effective coaching.",
  },
];

const Testimonials = ({
  num = "05",
  eyebrow = "In their words",
  heading = "What clients say after the work.",
  screenLabel = "05 Testimonials",
  bg = "var(--paper)",
} = {}) => {
  const items = TESTIMONIAL_ITEMS;
  const total = items.length;
  const [idx, setIdx] = useState(0);
  const [paused, setPaused] = useState(false);
  const [videoPlaying, setVideoPlaying] = useState(false);

  const next = () => { setVideoPlaying(false); setIdx((i) => (i + 1) % total); };
  const prev = () => { setVideoPlaying(false); setIdx((i) => (i - 1 + total) % total); };
  const goTo = (i) => { if (i !== idx) { setVideoPlaying(false); setIdx(i); } };

  // Auto-cycle — paused on hover or while a video is playing
  useEffect(() => {
    if (paused || videoPlaying) return;
    const id = setInterval(next, 12000);
    return () => clearInterval(id);
  }, [paused, videoPlaying, total]);

  // Keyboard nav
  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "ArrowRight") next();
      if (e.key === "ArrowLeft") prev();
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [total]);

  const item = items[idx];

  return (
    <section id="testimonials" data-screen-label={screenLabel} style={{ background: bg }}>
      <div className="wrap">
        <div style={{ marginBottom: 48 }}>
          <div className="eyebrow" style={{ marginBottom: 24 }}>
            <span className="num">{num}</span> {eyebrow}
          </div>
          <h2 className="h2" style={{ maxWidth: "20ch" }}>
            {heading}
          </h2>
        </div>

        {/* ── Rotator ──────────────────────────────────────────────────── */}
        <div
          onMouseEnter={() => setPaused(true)}
          onMouseLeave={() => setPaused(false)}
          style={{ position: "relative" }}
        >
          <ArrowBtn dir="left"  onClick={prev} label="Previous testimonial" />
          <ArrowBtn dir="right" onClick={next} label="Next testimonial" />

          {item.type === "video"
            ? <VideoSlide v={item} playing={videoPlaying} onPlay={() => setVideoPlaying(true)} />
            : <QuoteSlide q={item} />}
        </div>

        {/* ── Dots + counter ───────────────────────────────────────────── */}
        <div style={{
          marginTop: 28,
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          gap: 18,
          flexWrap: "wrap",
        }}>
          <div style={{ display: "flex", gap: 10 }}>
            {items.map((it, i) => (
              <button
                key={i}
                onClick={() => goTo(i)}
                aria-label={`Show testimonial ${i + 1}`}
                title={it.type === "video" ? "Video testimonial" : "Written testimonial"}
                style={{
                  width: i === idx ? 28 : (it.type === "video" ? 12 : 8),
                  height: 8,
                  borderRadius: 4,
                  border: it.type === "video" && i !== idx ? "1px solid var(--accent)" : "none",
                  background: i === idx
                    ? "var(--accent)"
                    : (it.type === "video" ? "transparent" : "var(--rule)"),
                  cursor: "pointer",
                  transition: "width 280ms ease, background 280ms ease",
                  padding: 0,
                }}
              />
            ))}
          </div>
          <div className="meta" style={{ color: "var(--ink-dim)" }}>
            {String(idx + 1).padStart(2, "0")} / {String(total).padStart(2, "0")}
            {item.type === "video" && <span style={{ color: "var(--accent-deep)", marginLeft: 8 }}>· Video</span>}
          </div>
        </div>
      </div>
    </section>
  );
};

/* ── Quote slide (written) ──────────────────────────────────────────── */
const QuoteSlide = ({ q }) => (
  <article style={{
    background: "var(--bg)",
    border: "1px solid var(--rule)",
    borderLeft: "3px solid var(--accent)",
    borderRadius: 12,
    padding: "44px 52px",
    display: "grid",
    gridTemplateColumns: "auto 1fr",
    gap: 40,
    alignItems: "start",
    minHeight: 300,
  }} className="t-card">
    <Avatar q={q} />

    <div>
      <Stars />
      <blockquote style={{
        margin: "20px 0 28px",
        fontFamily: "var(--sans)",
        fontWeight: 400,
        fontSize: "clamp(17px, 1.3vw, 19px)",
        lineHeight: 1.65,
        color: "var(--ink)",
        letterSpacing: "-0.005em",
      }}>
        <span style={{ color: "var(--accent)", fontWeight: 600 }}>“</span>
        {q.quote}
        <span style={{ color: "var(--accent)", fontWeight: 600 }}>”</span>
      </blockquote>
      <figcaption style={{
        display: "flex",
        justifyContent: "space-between",
        alignItems: "baseline",
        gap: 24,
        flexWrap: "wrap",
        paddingTop: 20,
        borderTop: "1px solid var(--rule)",
      }}>
        <div>
          <div style={{
            fontFamily: "var(--sans)",
            fontWeight: 600,
            fontSize: 17,
            color: "var(--ink)",
            letterSpacing: "-0.01em",
          }}>{q.name}</div>
          <div className="meta" style={{ marginTop: 4 }}>{q.role}</div>
        </div>
      </figcaption>
    </div>

    <style>{`
      @media (max-width: 760px) {
        .t-card {
          grid-template-columns: 1fr !important;
          gap: 22px !important;
          padding: 30px 24px !important;
          justify-items: start;
        }
      }
    `}</style>
  </article>
);

/* ── Video slide (YouTube) ──────────────────────────────────────────── */
const VideoSlide = ({ v, playing, onPlay }) => {
  const thumbUrl = v.thumb || `https://i.ytimg.com/vi/${v.id}/hqdefault.jpg`;
  return (
    <article style={{
      background: "var(--bg)",
      border: "1px solid var(--rule)",
      borderLeft: "3px solid var(--accent)",
      borderRadius: 12,
      padding: 16,
      display: "grid",
      gridTemplateColumns: "1.4fr 1fr",
      gap: 24,
      alignItems: "stretch",
      minHeight: 300,
    }} className="v-card">
      <div style={{
        aspectRatio: "16 / 9",
        position: "relative",
        background: "var(--ink)",
        borderRadius: 8,
        overflow: "hidden",
      }}>
        {playing
          ? <iframe
              key={v.id}
              src={`https://www.youtube-nocookie.com/embed/${v.id}?autoplay=1&rel=0`}
              title={v.name}
              frameBorder="0"
              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 }}
            />
          : <button
              onClick={onPlay}
              aria-label={`Play ${v.name}'s testimonial`}
              style={{
                position: "absolute", inset: 0, padding: 0, border: 0,
                cursor: "pointer",
                background: `center / cover no-repeat url(${thumbUrl})`,
                display: "flex", alignItems: "center", justifyContent: "center",
              }}
            >
              <span style={{
                width: 64, height: 64, borderRadius: "50%",
                background: "var(--accent)", color: "#fff",
                display: "flex", alignItems: "center", justifyContent: "center",
                boxShadow: "0 6px 22px rgba(0,0,0,0.35)",
              }}>
                <svg width="26" height="26" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M8 5v14l11-7z"/>
                </svg>
              </span>
            </button>}
      </div>

      <div style={{
        padding: "20px 16px",
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
      }}>
        <div className="meta" style={{ color: "var(--accent-deep)", marginBottom: 12 }}>
          Video testimonial
        </div>
        <div style={{
          fontFamily: "var(--sans)",
          fontWeight: 600,
          fontSize: 22,
          color: "var(--ink)",
          letterSpacing: "-0.02em",
          lineHeight: 1.2,
          marginBottom: 6,
        }}>{v.name}</div>
        <div className="meta" style={{ marginBottom: 20 }}>{v.role}</div>
        {!playing && (
          <button
            onClick={onPlay}
            className="btn"
            style={{
              alignSelf: "flex-start",
              background: "transparent",
              color: "var(--ink)",
              borderColor: "var(--ink)",
            }}
            onMouseEnter={(e) => { e.currentTarget.style.background = "var(--ink)"; e.currentTarget.style.color = "#fff"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "transparent"; e.currentTarget.style.color = "var(--ink)"; }}
          >
            Watch <span className="arrow">→</span>
          </button>
        )}
      </div>

      <style>{`
        @media (max-width: 760px) {
          .v-card { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </article>
  );
};

/* ── Avatar (photo or initials fallback) ────────────────────────────── */
const Avatar = ({ q, size = 96 }) => {
  if (q.photo) {
    return (
      <div style={{
        width: size, height: size,
        borderRadius: "50%",
        overflow: "hidden",
        flexShrink: 0,
        background: "var(--paper)",
        border: "1px solid var(--rule)",
      }}>
        <img
          src={q.photo}
          alt={q.name}
          style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
          onError={(e) => { e.target.style.display = "none"; }}
        />
      </div>
    );
  }
  const initials = q.name === "Anonymous"
    ? "❝"
    : q.name.split(" ").map((s) => s[0]).filter(Boolean).slice(0, 2).join("");
  return (
    <div 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",
      fontFamily: "var(--sans)",
      fontWeight: 500,
      fontSize: q.name === "Anonymous" ? size * 0.5 : size * 0.34,
      letterSpacing: q.name === "Anonymous" ? 0 : "-0.01em",
    }}>{initials}</div>
  );
};

/* ── Stars ──────────────────────────────────────────────────────────── */
const Stars = ({ n = 5 }) => (
  <div style={{ display: "flex", gap: 4 }}>
    {Array.from({ length: n }).map((_, i) => (
      <svg key={i} width="16" height="16" viewBox="0 0 24 24" fill="var(--accent)" aria-hidden="true">
        <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
      </svg>
    ))}
  </div>
);

/* ── Arrow nav button ───────────────────────────────────────────────── */
const ArrowBtn = ({ dir, onClick, label }) => (
  <button
    onClick={onClick}
    aria-label={label}
    style={{
      position: "absolute",
      top: "50%",
      [dir]: -24,
      transform: "translateY(-50%)",
      width: 44, height: 44,
      borderRadius: "50%",
      background: "var(--paper)",
      border: "1px solid var(--rule)",
      color: "var(--ink)",
      cursor: "pointer",
      display: "flex", alignItems: "center", justifyContent: "center",
      boxShadow: "0 2px 8px rgba(10, 31, 61, 0.04)",
      zIndex: 2,
      transition: "background 180ms ease, color 180ms ease, border-color 180ms ease",
    }}
    onMouseEnter={(e) => { e.currentTarget.style.background = "var(--ink)"; e.currentTarget.style.color = "var(--bg)"; e.currentTarget.style.borderColor = "var(--ink)"; }}
    onMouseLeave={(e) => { e.currentTarget.style.background = "var(--paper)"; e.currentTarget.style.color = "var(--ink)"; e.currentTarget.style.borderColor = "var(--rule)"; }}
  >
    <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>
);

window.Testimonials = Testimonials;
