/* global React */
const { useEffect: useQuoteEffect, useRef: useQuoteRef } = React;

function QuoteGrid({ quotes }) {
  // Quotes come in groups of 3; the second row of the original mockup is faded.
  const rows = [];
  for (let i = 0; i < quotes.length; i += 3) rows.push(quotes.slice(i, i + 3));

  return (
    <section className="cc-quotes">
      {rows.map((row, ri) => (
        <div
          key={ri}
          className={`cc-quote-row ${ri === rows.length - 1 && rows.length > 1 ? 'cc-quote-faded' : ''}`}
        >
          {row.map((q, qi) => (
            <RevealQuote key={qi} text={q.text} attr={q.attr} role={q.role} index={ri * 3 + qi} />
          ))}
        </div>
      ))}
    </section>
  );
}

// Card that fades + lifts into place when it scrolls into view.
function RevealQuote({ text, attr, role, index = 0 }) {
  const ref = useQuoteRef(null);
  useQuoteEffect(() => {
    const el = ref.current;
    if (!el) return;
    // Respect reduced-motion: skip the reveal animation entirely.
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      el.classList.add('cc-quote-in');
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        for (const e of entries) {
          if (e.isIntersecting) {
            el.classList.add('cc-quote-in');
            io.unobserve(el);
          }
        }
      },
      { threshold: 0.18 }
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  return (
    <article
      ref={ref}
      className="cc-quote-card"
      style={{ transitionDelay: `${(index % 3) * 80}ms` }}
    >
      <p className="cc-quote-text">&ldquo;{text}&rdquo;</p>
      <p className="cc-quote-attr">{attr}</p>
      {role && <p className="cc-quote-role">{role}</p>}
    </article>
  );
}

window.QuoteGrid = QuoteGrid;
