// Recursive MLS — shared map component (the DEFAULT map system across the platform).
//
// Wraps the Local Logic "local-content" SDK (https://docs.locallogic.co), branded to
// the Recursive palette. Use <LocalLogicMap> anywhere the product shows a map.
//
// Listing-pin CLUSTERING is NOT part of the local-content SDK — it is a custom overlay
// the dev team wires onto this base map in Claude Code. This component therefore renders
// the real Local Logic base map and accepts overlay `children` (clusters / pins / controls)
// positioned on top. See BuyerSearch.jsx for the clusters-zoomed-out spec.

const LL_API_KEY = "V3 BuhK7Tn8anFPtohd1ov78tsJE2oHthHM.505282f0-f6f5-4538-8999-ac939b3cfff3";
const LL_VERSION = "1.22.16";

// Recursive brand appearance for every Local Logic widget.
const LL_APPEARANCE = {
  variables: {
    "--ll-color-primary": "#006747",          // Pantone 342 C
    "--ll-color-primary-variant1": "#00543A", // pressed / deeper green
    "--ll-font-family": "'Space Grotesk', sans-serif",
  },
};

// Branded base shown while the SDK boots, or if it can't paint (e.g. key not yet
// allow-listed for this origin). Keeps the pane intentional — never blank.
function LocalLogicFallback({ status }) {
  return (
    <div style={{ position: "absolute", inset: 0, background: "#e8ebe5", overflow: "hidden" }}>
      <svg width="100%" height="100%" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid slice" style={{ position: "absolute", inset: 0 }}>
        <rect width="100" height="100" fill="#e8ebe5" />
        <path d="M-5 70 Q 25 60 45 72 T 105 68 L105 105 L-5 105 Z" fill="#d2dee0" />
        <rect x="58" y="12" width="26" height="20" rx="2" fill="#d8e6d4" />
        <g stroke="#ffffff" strokeWidth="2.4" strokeLinecap="round">
          <line x1="0" y1="22" x2="100" y2="18" /><line x1="0" y1="46" x2="100" y2="44" />
          <line x1="0" y1="64" x2="55" y2="63" /><line x1="20" y1="0" x2="24" y2="100" />
          <line x1="48" y1="0" x2="50" y2="100" /><line x1="76" y1="0" x2="78" y2="66" />
        </g>
        <g stroke="#ffffff" strokeWidth="1.1" strokeLinecap="round" opacity="0.8">
          <line x1="0" y1="33" x2="100" y2="31" /><line x1="0" y1="55" x2="55" y2="54" />
          <line x1="34" y1="0" x2="36" y2="62" /><line x1="62" y1="0" x2="64" y2="66" /><line x1="88" y1="0" x2="90" y2="64" />
        </g>
        <text x="70" y="23" fontSize="3" fill="#7fa07a" fontFamily="'Space Grotesk'" fontWeight="600">PEASE PARK</text>
        <text x="14" y="80" fontSize="3" fill="#8fa6ab" fontFamily="'Space Grotesk'" fontWeight="600">LADY BIRD LAKE</text>
      </svg>
      <div style={{ position: "absolute", left: 14, bottom: 14, display: "inline-flex", alignItems: "center", gap: 7,
        background: "rgba(255,255,255,.94)", borderRadius: 7, padding: "7px 11px", boxShadow: "0 1px 6px rgba(0,0,0,.14)" }}>
        <span style={{ width: 8, height: 8, borderRadius: "50%", background: status === "error" ? "#c0612f" : "#006747",
          ...(status === "loading" ? { animation: "rc-spin 1s linear infinite" } : {}) }} />
        <span style={{ fontSize: 11.5, fontWeight: 600, color: "#4a504a" }}>
          {status === "error" ? "Local Logic map — live in production" : "Loading Local Logic map…"}
        </span>
      </div>
    </div>
  );
}

function LocalLogicMap({ lat = 30.2849, lng = -97.7341, zoom = 12, marker = null, scores = false, children, style }) {
  const hostRef = React.useRef(null);
  const instRef = React.useRef(null);
  const [status, setStatus] = React.useState("loading"); // loading | ready | error

  // boot once
  React.useEffect(() => {
    let cancelled = false, tries = 0;
    const boot = () => {
      if (cancelled || !hostRef.current) return;
      const SDK = window.LLSDKsJS || window.LocalLogicSDK;
      if (typeof SDK !== "function") {
        if (tries++ > 80) setStatus("error");
        else setTimeout(boot, 150);
        return;
      }
      try {
        const client = SDK(LL_API_KEY, { locale: "en", appearance: LL_APPEARANCE });
        const opts = { lat, lng, zoom, cooperativeGestures: true, showSchoolRatings: true, scoresMenu: { defaultOpen: scores } };
        if (marker) opts.marker = marker;
        instRef.current = client.create("local-content", hostRef.current, opts);
        // create() can return without throwing yet never paint (e.g. the API key
        // isn't allow-listed for this origin). Confirm a real iframe appears before
        // hiding the branded base layer; otherwise leave the base shown.
        let checks = 0;
        const confirm = () => {
          if (cancelled || !hostRef.current) return;
          if (hostRef.current.querySelector("iframe")) { setStatus("ready"); return; }
          if (checks++ > 30) { setStatus("error"); return; }
          setTimeout(confirm, 200);
        };
        confirm();
      } catch (e) {
        console.warn("[LocalLogicMap] init failed:", e);
        setStatus("error");
      }
    };
    boot();
    return () => { cancelled = true; try { instRef.current && instRef.current.destroy && instRef.current.destroy(); } catch (e) {} };
  }, []);

  // recenter / re-zoom when the caller changes coordinates
  React.useEffect(() => {
    const inst = instRef.current;
    if (inst && inst.update && status === "ready") {
      try {
        const opts = { lat, lng, zoom };
        if (marker) opts.marker = marker;
        inst.update(opts);
      } catch (e) {}
    }
  }, [lat, lng, zoom, marker && marker.lat, marker && marker.lng, status]);

  return (
    <div style={{ position: "relative", width: "100%", height: "100%", overflow: "hidden", background: "#e8ebe5", ...style }}>
      {/* branded base layer — always present so the pane is never blank; the real
          Local Logic widget paints into the host above and covers it when authorized. */}
      {status !== "ready" && <LocalLogicFallback status={status} />}
      <div ref={hostRef} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", zIndex: 1 }} />
      {children}
    </div>
  );
}

window.LocalLogicMap = LocalLogicMap;
