// Reviews — Elfsight Google Reviews widget with a graceful static fallback.
//
// Why this is more than a one-liner:
//  • platform.js was originally loaded with `async` in <head>. With Babel
//    standalone compiling React in the browser, the widget div didn't exist
//    when platform.js first scanned the DOM, so for some visitors (incognito,
//    strict tracking protection, Firefox ETP) the MutationObserver fallback
//    never caught the node and the widget stayed blank.
//  • Elfsight's free tier also has a monthly view cap; once hit, the iframe
//    simply never renders for anyone — a silent failure that looks like a bug.
//
// Fix: the component itself (re)injects platform.js after React has mounted
// the widget div, then watches for a rendered iframe. If nothing shows up
// within ~6 seconds we reveal a static "Read all reviews on Google" panel so
// visitors always see a working reviews section.

const REVIEWS_DEFAULTS = {
  elfsightAppId: '37170ab3-04e8-4238-9c90-9d93f6660017',
  rating: 4.8,
  count: '500+',
  googleHref: 'https://maps.google.com/maps?cid=9967761230453159991',
  fallbackCta: 'Read all reviews on Google',
};

const ELFSIGHT_SRC = 'https://elfsightcdn.com/platform.js';
const WIDGET_TIMEOUT_MS = 6000;

// TripAdvisor Certificate of Excellence (2016) — awarded location 2392184.
// The wejs script hydrates the pre-rendered <ul> markup with a live badge.
const TRIPADVISOR_SRC =
  'https://www.jscache.com/wejs?wtype=certificateOfExcellence&uniq=264&locationId=2392184&lang=en_US&year=2016&display_version=2';
const TRIPADVISOR_HREF =
  'https://www.tripadvisor.com/Restaurant_Review-g488103-d2392184-Reviews-Sunset_Cafe_Restaurant_Grand_Baie-Grand_Baie.html';

function Reviews({ data }) {
  const reviews = (data && data.reviews) ? { ...REVIEWS_DEFAULTS, ...data.reviews } : REVIEWS_DEFAULTS;

  const headingRef = React.useRef(null);
  const widgetRef  = React.useRef(null);
  const firedRef   = React.useRef(false);

  const [showFallback, setShowFallback] = React.useState(false);

  // Intro animation — unchanged from the original component.
  React.useEffect(() => {
    if (firedRef.current) return;
    if (typeof gsap === 'undefined' || typeof ScrollTrigger === 'undefined') return;
    firedRef.current = true;

    if (headingRef.current) {
      gsap.fromTo(headingRef.current,
        { opacity: 0, y: 30 },
        {
          opacity: 1, y: 0, duration: 0.7, ease: 'power3.out',
          scrollTrigger: { trigger: headingRef.current, start: 'top 85%', once: true },
        });
    }
    if (widgetRef.current) {
      gsap.fromTo(widgetRef.current,
        { opacity: 0, y: 24 },
        {
          opacity: 1, y: 0, duration: 0.8, ease: 'power2.out',
          scrollTrigger: { trigger: widgetRef.current, start: 'top 90%', once: true },
        });
    }
  }, []);

  // Load platform.js, force a re-scan, and fall back if nothing renders.
  React.useEffect(() => {
    // Re-inject the script so it re-scans the DOM now that the widget div
    // is actually mounted. If it's already on the page we remove it first
    // — just adding a duplicate <script> won't retrigger the scan.
    const existing = document.querySelector(`script[src="${ELFSIGHT_SRC}"]`);
    if (existing && existing.parentNode) existing.parentNode.removeChild(existing);

    const s = document.createElement('script');
    s.src = ELFSIGHT_SRC;
    s.async = true;
    document.head.appendChild(s);

    // Watch the widget host for a rendered iframe / Elfsight-generated node.
    // If neither appears within the timeout, reveal the static fallback.
    let settled = false;
    const markRendered = () => {
      settled = true;
      setShowFallback(false);
      if (observer) observer.disconnect();
      clearTimeout(timer);
    };

    const hostEl = widgetRef.current;
    const hasWidgetContent = () => {
      if (!hostEl) return false;
      return !!hostEl.querySelector('iframe, [class*="eapps-"], [class*="elfsight-"]:not([class="elfsight-app-' + reviews.elfsightAppId + '"])');
    };

    let observer = null;
    if (hostEl && typeof MutationObserver !== 'undefined') {
      observer = new MutationObserver(() => {
        if (hasWidgetContent()) markRendered();
      });
      observer.observe(hostEl, { childList: true, subtree: true });
    }

    const timer = setTimeout(() => {
      if (settled) return;
      if (!hasWidgetContent()) setShowFallback(true);
    }, WIDGET_TIMEOUT_MS);

    return () => {
      clearTimeout(timer);
      if (observer) observer.disconnect();
    };
  }, [reviews.elfsightAppId]);

  // Inject TripAdvisor wejs once. The script reads any
  // #TA_certificateOfExcellence* node already in the DOM and hydrates it.
  React.useEffect(() => {
    if (document.querySelector(`script[src="${TRIPADVISOR_SRC}"]`)) return;
    const s = document.createElement('script');
    s.src = TRIPADVISOR_SRC;
    s.async = true;
    document.body.appendChild(s);
  }, []);

  const stars = '★★★★★';

  return (
    <section id="reviews">
      <div className="reviews-header" ref={headingRef}>
        <p className="reviews-label">WHAT GUESTS SAY</p>
        <h2 className="reviews-heading">Google Reviews</h2>
      </div>
      <div className="reviews-widget-wrap" ref={widgetRef}>
        <div className={`elfsight-app-${reviews.elfsightAppId}`} />

        {showFallback && (
          <div className="reviews-fallback" role="complementary" aria-label="Google reviews summary">
            <div className="reviews-fallback-stars" aria-hidden="true">{stars}</div>
            <p className="reviews-fallback-rating">
              <strong>{reviews.rating}</strong> / 5 on Google
            </p>
            <p className="reviews-fallback-sub">{reviews.count} guest reviews</p>
            <a
              className="reviews-fallback-cta"
              href={reviews.googleHref}
              target="_blank"
              rel="noopener noreferrer"
            >
              <span>{reviews.fallbackCta}</span>
            </a>
          </div>
        )}
      </div>

      <div className="reviews-awards" aria-label="TripAdvisor Certificate of Excellence">
        <p className="reviews-awards-caption">Recognised by TripAdvisor</p>
        <div id="TA_certificateOfExcellence264" className="TA_certificateOfExcellence">
          <ul id="Np1QtJCM" className="TA_links Eb0DASpDQH5">
            <li id="IKazFor3WxX" className="N5DW7kzD">
              <a target="_blank" rel="noopener noreferrer" href={TRIPADVISOR_HREF}>
                <img
                  src="https://www.tripadvisor.com/img/cdsi/img2/awards/v2/coe-14348-2.png"
                  alt="TripAdvisor Certificate of Excellence 2016"
                  className="widCOEImg"
                  id="CDSWIDCOELOGO"
                  loading="lazy"
                  decoding="async"
                />
              </a>
            </li>
          </ul>
        </div>
      </div>
    </section>
  );
}
