// TESTIMONIALS. dark ceremonial theatre. Real client video + voice reflections.
// Data-driven: add another { } to TESTIMONIALS or AUDIO_TESTIMONIALS to grow it.
// Videos are web-optimized (H.264 High, +faststart, baked rotation, yuv420p) and
// use preload="metadata"; audio is MP3 (universal, incl. iOS) with preload="none",
// so nothing heavy loads until the visitor presses play keeps the page fast.

const TESTIMONIALS = [
  {
    src: 'assets/testimonial-1.mp4',
    poster: 'assets/testimonial-1.jpg',
    orientation: 'portrait',
    label: 'In Their Own Words',
    sub: 'Cosmic Healing · Testimonial',
  },
  {
    src: 'assets/testimonial-2.mp4',
    poster: 'assets/testimonial-2.jpg',
    orientation: 'portrait',
    label: 'A Voice of Remembrance',
    sub: 'Cosmic Healing · Testimonial',
  },
];

// Order note: audio-1 has a few seconds of silent lead-in, so it sits last (04).
const AUDIO_TESTIMONIALS = [
  { src: 'assets/audio-2.mp3', label: 'Voice Reflection · 01', duration: '0:57' },
  { src: 'assets/audio-3.mp3', label: 'Voice Reflection · 02', duration: '1:57' },
  { src: 'assets/audio-1.mp3', label: 'Voice Reflection · 03', duration: '1:12' },
];

// Only one testimonial (video OR audio) plays at a time keep it calm and smooth.
function pauseOtherMedia(current) {
  document.querySelectorAll('video.tm-video, audio.tm-audio').forEach((el) => {
    if (el !== current) el.pause();
  });
}

// Deterministic pseudo-random bar heights (0.30..1.0) a stable faux waveform.
const WAVE_BARS = Array.from({ length: 36 }, (_, i) => {
  const n = Math.sin((i + 1) * 12.9898) * 43758.5453;
  return 0.30 + (n - Math.floor(n)) * 0.70;
});

function fmtTime(s) {
  if (!isFinite(s) || s < 0) s = 0;
  const m = Math.floor(s / 60);
  const sec = Math.floor(s % 60);
  return `${m}:${String(sec).padStart(2, '0')}`;
}

function TestimonialVideo({ src, poster, label }) {
  const ref = useRef(null);
  const [started, setStarted] = useState(false);

  const play = () => {
    const v = ref.current;
    if (!v) return;
    pauseOtherMedia(v);
    const p = v.play();
    if (p && p.catch) p.catch(() => {});
    setStarted(true);
  };

  const reset = () => {
    setStarted(false);
    const v = ref.current;
    if (v) v.load(); // restore the poster frame once it finishes
  };

  return (
    <div className="tm-video-frame">
      <video
        ref={ref}
        className="tm-video"
        src={src}
        poster={poster}
        preload="metadata"
        playsInline
        controls={started}
        controlsList="nodownload"
        onEnded={reset}
      />
      {!started && (
        <button
          type="button"
          className="tm-video__overlay"
          onClick={play}
          aria-label={`Play testimonial — ${label}`}
        >
          <span className="tm-video__glow" aria-hidden="true" />
          <span className="tm-video__play" aria-hidden="true">
            <svg viewBox="0 0 24 24" width="30" height="30">
              <path d="M8 5.3 L18.6 12 L8 18.7 Z" fill="currentColor" />
            </svg>
          </span>
          <span className="tm-video__hint">Watch</span>
        </button>
      )}
    </div>
  );
}

function AudioTestimonial({ src, label, duration }) {
  const ref = useRef(null);
  const [playing, setPlaying] = useState(false);
  const [progress, setProgress] = useState(0); // 0..1
  const [elapsed, setElapsed] = useState(0);

  const toggle = () => {
    const a = ref.current;
    if (!a) return;
    if (a.paused) {
      pauseOtherMedia(a);
      const p = a.play();
      if (p && p.catch) p.catch(() => {});
    } else {
      a.pause();
    }
  };

  const onTime = () => {
    const a = ref.current;
    if (!a) return;
    const dur = a.duration || 0;
    setElapsed(a.currentTime);
    setProgress(dur ? a.currentTime / dur : 0);
  };

  const seek = (e) => {
    const a = ref.current;
    if (!a) return;
    const rect = e.currentTarget.getBoundingClientRect();
    const ratio = Math.min(1, Math.max(0, (e.clientX - rect.left) / rect.width));
    if (a.duration) {
      a.currentTime = ratio * a.duration;
      setProgress(ratio);
      setElapsed(ratio * a.duration);
    }
  };

  return (
    <div className={`tm-audio-card ${playing ? 'is-playing' : ''}`}>
      <audio
        ref={ref}
        className="tm-audio"
        src={src}
        preload="none"
        onPlay={() => setPlaying(true)}
        onPause={() => setPlaying(false)}
        onEnded={() => { setPlaying(false); setProgress(0); setElapsed(0); }}
        onTimeUpdate={onTime}
      />
      <button
        type="button"
        className="tm-audio__btn"
        onClick={toggle}
        aria-label={`${playing ? 'Pause' : 'Play'} — ${label}`}
      >
        {playing ? (
          <svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true">
            <rect x="6" y="5" width="4" height="14" rx="1" fill="currentColor" />
            <rect x="14" y="5" width="4" height="14" rx="1" fill="currentColor" />
          </svg>
        ) : (
          <svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true">
            <path d="M8 5.3 L18.6 12 L8 18.7 Z" fill="currentColor" />
          </svg>
        )}
      </button>
      <div className="tm-audio__body">
        <span className="tm-audio__label">{label}</span>
        <div className="tm-audio__row">
          <div
            className="tm-audio__wave"
            onClick={seek}
            role="progressbar"
            aria-label={label}
            aria-valuemin="0"
            aria-valuemax="100"
            aria-valuenow={Math.round(progress * 100)}
          >
            {WAVE_BARS.map((h, i) => (
              <span
                key={i}
                className={`tm-audio__bar ${i / WAVE_BARS.length < progress ? 'is-played' : ''}`}
                style={{ height: `${Math.round(h * 100)}%` }}
              />
            ))}
          </div>
          <span className="tm-audio__time">
            {elapsed > 0 ? `${fmtTime(elapsed)} / ${duration}` : duration}
          </span>
        </div>
      </div>
    </div>
  );
}

function Testimonials() {
  return (
    <section className="section testimonials scales" id="testimonials">
      <div className="container">
        <Reveal as="div" className="testimonials__head">
          <Eyebrow tone="gold">Testimonials · Real Reflections</Eyebrow>
          <h2 className="h-section">Voices of Those Who Remembered.</h2>
          <p className="sub-italic">
            Unscripted reflections from souls who walked through the fire
            and came home to themselves.
          </p>
        </Reveal>

        <div className={`testimonials__grid ${TESTIMONIALS.length === 1 ? 'testimonials__grid--single' : ''}`}>
          {TESTIMONIALS.map((t, i) => (
            <Reveal
              as="div"
              key={t.src}
              className={`tm-card tm-card--${t.orientation}`}
              delay={100 + i * 150}
              threshold={0.18}
            >
              <TestimonialVideo {...t} />
              <div className="tm-card__caption">
                <span className="tm-card__label">{t.label}</span>
                <span className="tm-card__sub">{t.sub}</span>
              </div>
            </Reveal>
          ))}
        </div>

        <Reveal as="div" className="testimonials__audio-head" delay={80} threshold={0.2}>
          <Eyebrow tone="gold">Heard, Not Seen · Voice Reflections</Eyebrow>
        </Reveal>

        <div className="tm-audio-grid">
          {AUDIO_TESTIMONIALS.map((a, i) => (
            <Reveal
              as="div"
              key={a.src}
              className="tm-audio-cell"
              delay={100 + i * 90}
              threshold={0.15}
            >
              <AudioTestimonial {...a} />
            </Reveal>
          ))}
        </div>
      </div>
    </section>
  );
}

window.Testimonials = Testimonials;
