// Location — satellite map finale section.
// Sits between Gallery (cream) and Footer (charcoal).
//
// Reliability pattern: the Google Maps satellite embed occasionally renders
// as a grey tile or never actually paints. Since cross-origin iframes can't
// be inspected from the parent page, the only way to guarantee a consistent
// panel is click-to-load. Default state shows a designed card (exterior
// photo + address + CTA). The interactive iframe only mounts after the user
// explicitly asks for it, and the "Open in Google Maps" chip is always
// visible as an escape hatch in every state.
//
// Animations (GSAP + ScrollTrigger):
//   - Map frame: scale 0.98 → 1 + fade, 900ms power2.out.
//   - CTA: fade + y16 → 0, 600ms power2.out.

function Location({ data }) {
  const sectionRef = React.useRef(null);
  const mapRef     = React.useRef(null);
  const ctaRef     = React.useRef(null);
  const firedRef   = React.useRef(false);

  const [mapRequested, setMapRequested] = React.useState(false);
  const [mapLoaded, setMapLoaded] = React.useState(false);

  React.useEffect(() => {
    if (!data || !data.location) return;
    if (firedRef.current) return;
    if (typeof gsap === 'undefined' || typeof ScrollTrigger === 'undefined') return;
    firedRef.current = true;

    if (mapRef.current) {
      gsap.fromTo(mapRef.current,
        { opacity: 0, scale: 0.97 },
        {
          opacity: 1, scale: 1, duration: 0.9, ease: 'power2.out',
          scrollTrigger: { trigger: mapRef.current, start: 'top 90%', once: true },
        });
    }
    if (ctaRef.current) {
      gsap.fromTo(ctaRef.current,
        { opacity: 0, y: 16 },
        {
          opacity: 1, y: 0, duration: 0.6, ease: 'power2.out',
          scrollTrigger: { trigger: ctaRef.current, start: 'top 95%', once: true },
        });
    }

    const refresh = setTimeout(() => ScrollTrigger.refresh(), 300);
    return () => clearTimeout(refresh);
  }, [data]);

  if (!data || !data.location) return null;
  const loc = data.location;

  const fallbackImg = (data.about && data.about.image)
    || './brand_assets/images/exterior/terrace-sunset-harbor-silhouette.webp';

  const directionsHref = (loc.cta && loc.cta.href)
    || 'https://maps.google.com/maps?cid=9967761230453159991';

  return (
    <section id="location" ref={sectionRef}>
      <div className="location-map-frame" ref={mapRef}>
        <div className="location-map-stage">
          {/* Designed fallback card — the default state. */}
          <div
            className="location-map-fallback"
            aria-hidden={mapRequested ? 'true' : 'false'}
          >
            <img
              src={fallbackImg}
              alt=""
              className="location-map-fallback-img"
              loading="lazy"
              aria-hidden="true"
            />
            <div className="location-map-fallback-card">
              <p className="location-map-fallback-eyebrow">Find us</p>
              <p className="location-map-fallback-address">
                {loc.address || 'La Salette Road, Grand Baie, Mauritius'}
              </p>
              <div className="location-map-fallback-actions">
                <button
                  type="button"
                  className="location-map-fallback-btn"
                  onClick={() => setMapRequested(true)}
                  aria-label="View interactive satellite map"
                >
                  <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <polygon points="1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6"/>
                    <line x1="8" y1="2" x2="8" y2="18"/>
                    <line x1="16" y1="6" x2="16" y2="22"/>
                  </svg>
                  <span>View satellite map</span>
                </button>
                <a
                  href={directionsHref}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="location-map-fallback-link"
                >
                  <span>Open in Google Maps</span>
                  <svg viewBox="0 0 24 24" width="11" height="11" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>
                    <polyline points="15 3 21 3 21 9"/>
                    <line x1="10" y1="14" x2="21" y2="3"/>
                  </svg>
                </a>
              </div>
            </div>
          </div>

          {/* Iframe mounts only after the user clicks "View satellite map". */}
          {mapRequested && (
            <iframe
              className={mapLoaded ? 'location-map is-loaded' : 'location-map'}
              src={loc.mapSrc}
              loading="lazy"
              title={`Satellite view of ${loc.address || 'Sunset Restaurant'}`}
              referrerPolicy="no-referrer-when-downgrade"
              allowFullScreen
              onLoad={() => setMapLoaded(true)}
            />
          )}

          {/* Persistent escape-hatch chip — always visible above everything. */}
          <a
            href={directionsHref}
            target="_blank"
            rel="noopener noreferrer"
            className="location-map-chip"
            aria-label="Open in Google Maps"
          >
            <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
              <circle cx="12" cy="10" r="3"/>
            </svg>
            <span>Open in Maps</span>
          </a>
        </div>
      </div>

      {loc.cta && loc.cta.label && (
        <div className="location-cta" ref={ctaRef}>
          <a
            href={loc.cta.href}
            target="_blank"
            rel="noopener noreferrer"
            className="location-cta-btn"
          >
            <span>{loc.cta.label}</span>
            <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M5 12h14M13 5l7 7-7 7"/></svg>
          </a>
        </div>
      )}
    </section>
  );
}
