// Recursive MLS — Screen 3: Find homes for a client (split map + results).
function BuyerSearch({ layout = "split", onOpen }) {
  const D = window.RC_DATA;
  const [sel, setSel] = useState("S-1");
  const [hover, setHover] = useState(null);
  const [zoom, setZoom] = useState(12); // map zoom — drives auto clustering (out) vs pins (in)
  const [favs, setFavs] = useState(() => new Set(D.searchResults.filter((r) => r.fav).map((r) => r.id)));
  const toggleFav = (id) => {
    const n = new Set(favs); n.has(id) ? n.delete(id) : n.add(id); setFavs(n);
  };
  const results = D.searchResults;

  const filters = [
    { label: "$450K – $1.2M", icon: "circle-dollar-sign" },
    { label: "3+ beds", icon: "bed-double" },
    { label: "2+ baths", icon: "bath" },
    { label: "House, Condo", icon: "home" },
  ];

  // ---- result card ----
  const ResultCard = ({ r, compact }) => {
    const active = sel === r.id;
    const isFav = favs.has(r.id);
    return (
      <div onMouseEnter={() => setHover(r.id)} onMouseLeave={() => setHover(null)} onClick={() => (onOpen ? onOpen(r) : setSel(r.id))}
        style={{ background: "#fff", borderRadius: 4, cursor: "pointer", overflow: "hidden",
          boxShadow: active ? "0 0 0 2px #006747, 0 4px 14px rgba(0,0,0,.1)" : "inset 0 0 0 1px rgba(0,0,0,.08)",
          transition: "box-shadow .12s", display: compact ? "flex" : "block" }}>
        <div style={{ position: "relative", flex: compact ? "none" : "auto", width: compact ? 150 : "auto",
          aspectRatio: compact ? "auto" : "3/2", height: compact ? 112 : "auto",
          backgroundImage: `url(${r.photos[0]})`, backgroundSize: "cover", backgroundPosition: "center" }}>
          <span style={{ position: "absolute", top: 9, left: 9 }}>
            <Pill tone={r.status === "Price ↓" ? "drop" : r.status === "New" ? "new" : "active"}>{r.status}</Pill>
          </span>
          <button onClick={(e) => { e.stopPropagation(); toggleFav(r.id); }}
            style={{ position: "absolute", top: 9, right: 9, width: 28, height: 28, borderRadius: "50%", border: 0,
              background: "rgba(255,255,255,.92)", display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}>
            <Icon name="heart" size={14} color={isFav ? "#c0612f" : "#4a504a"} style={isFav ? { fill: "#c0612f" } : {}} />
          </button>
          {!compact && <span style={{ position: "absolute", bottom: 9, left: 9, fontSize: 10.5, fontWeight: 600, color: "#fff", background: "rgba(0,0,0,.55)", padding: "3px 8px", borderRadius: 999 }}>{r.match}% match</span>}
        </div>
        <div style={{ padding: compact ? "11px 13px" : 14, flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8 }}>
            <span style={{ fontFamily: "'Space Mono', monospace", fontSize: compact ? 16 : 19, fontWeight: 700, color: "#1d241f", letterSpacing: "-0.5px" }}>{D.usd(r.price)}</span>
            {compact && <span style={{ fontSize: 11, fontWeight: 600, color: "#006747" }}>{r.match}%</span>}
          </div>
          <div style={{ display: "flex", gap: 11, fontSize: 12.5, color: "#4a504a", margin: "6px 0 7px" }}>
            <span><strong>{r.beds}</strong> bd</span><span style={{ color: "#e0ded6" }}>·</span>
            <span><strong>{r.baths}</strong> ba</span><span style={{ color: "#e0ded6" }}>·</span>
            <span><strong>{r.sqft.toLocaleString()}</strong> sqft</span>
          </div>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.addr}</div>
          <div style={{ fontSize: 12.5, color: "#8a8e88", marginTop: 2 }}>{r.city}</div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 9 }}>
            <span style={{ fontSize: 11.5, color: "#a8aca6" }}>{r.type} · {r.dom}d on market</span>
            {onOpen
              ? <span style={{ fontSize: 11.5, fontWeight: 600, color: "#006747", display: "inline-flex", alignItems: "center", gap: 3 }}>View details <Icon name="chevron-right" size={13} color="#006747" /></span>
              : (isFav && <span style={{ fontSize: 11, fontWeight: 600, color: "#c0612f", display: "inline-flex", alignItems: "center", gap: 4 }}><Icon name="check" size={12} color="#c0612f" /> Shared</span>)}
          </div>
        </div>
      </div>
    );
  };

  // ---- map: real Local Logic base (the default Recursive map system) + listing overlay ----
  // NOTE: listing CLUSTERS are a custom overlay on the Local Logic base map; the dynamic
  // zoom/cluster math gets wired in Claude Code. Below shows the intended visual at low zoom.
  const clusterData = [
    { id: "cl-1", top: "33%", left: "39%", count: 23 },
    { id: "cl-2", top: "57%", left: "29%", count: 14 },
    { id: "cl-3", top: "29%", left: "66%", count: 9 },
    { id: "cl-4", top: "68%", left: "61%", count: 6 },
  ];
  const clusterSize = (n) => (n >= 20 ? 56 : n >= 12 ? 50 : n >= 7 ? 44 : 38);

  const ClusterBubble = ({ c }) => {
    const d = clusterSize(c.count);
    return (
      <button onClick={() => setZoom(14)} title={`${c.count} listings · zoom in`}
        style={{ position: "absolute", top: c.top, left: c.left, transform: "translate(-50%,-50%)", pointerEvents: "auto",
          width: d, height: d, borderRadius: "50%", border: "3px solid #fff", cursor: "pointer",
          background: "#006747", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center",
          fontFamily: "'Space Mono', monospace", fontWeight: 700, fontSize: c.count >= 20 ? 17 : 15,
          boxShadow: "0 3px 12px rgba(0,40,28,.35), 0 0 0 6px rgba(0,103,71,.16)" }}>
        {c.count}
      </button>
    );
  };

  const MapCanvas = () => {
    const selR = results.find((r) => r.id === sel) || results[0];
    // Auto-cluster: at low zoom show clusters; as you zoom in they resolve to individual pins.
    const showClusters = zoom <= 12;
    const zoomIn = () => setZoom((z) => Math.min(16, z + 1));
    const zoomOut = () => setZoom((z) => Math.max(10, z - 1));
    return (
      <LocalLogicMap lat={30.2849} lng={-97.7341} zoom={zoom}
        marker={showClusters ? null : { lat: 30.2849, lng: -97.7341, icon: "pin" }}>
        {/* overlay layer — transparent to map gestures except interactive chips */}
        <div style={{ position: "absolute", inset: 0, pointerEvents: "none", zIndex: 6 }}>

          {/* listing overlay auto-switches: clusters when zoomed out, price pins when zoomed in */}
          {showClusters
            ? clusterData.map((c) => <ClusterBubble key={c.id} c={c} />)
            : results.map((r) => {
                const on = sel === r.id || hover === r.id;
                const isFav = favs.has(r.id);
                return (
                  <button key={r.id} onClick={() => setSel(r.id)} onMouseEnter={() => setHover(r.id)} onMouseLeave={() => setHover(null)}
                    style={{ position: "absolute", top: `${r.lat}%`, left: `${r.lng}%`, transform: "translate(-50%,-50%)", pointerEvents: "auto",
                      zIndex: on ? 5 : isFav ? 3 : 1, border: 0, cursor: "pointer", borderRadius: 999,
                      fontFamily: "'Space Mono', monospace", fontWeight: 700, fontSize: 12,
                      padding: "5px 10px", whiteSpace: "nowrap", transition: "all .12s",
                      background: on ? "#006747" : "#fff", color: on ? "#fff" : isFav ? "#c0612f" : "#1d241f",
                      boxShadow: on ? "0 4px 12px rgba(0,0,0,.28)" : "0 1px 4px rgba(0,0,0,.22)",
                      outline: isFav && !on ? "1.5px solid #c0612f" : "none" }}>
                    {D.usd(Math.round(r.price / 1000)) + "K"}
                  </button>
                );
              })}

          {/* zoom controls (top-right) — zooming in resolves clusters into individual pins */}
          <div style={{ position: "absolute", top: 14, right: 14, display: "flex", flexDirection: "column", borderRadius: 7, overflow: "hidden", pointerEvents: "auto", boxShadow: "0 2px 8px rgba(0,0,0,.18)" }}>
            <button onClick={zoomIn} title="Zoom in" style={{ width: 34, height: 34, border: 0, borderBottom: "1px solid #ececec", background: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name="plus" size={16} color="#4a504a" />
            </button>
            <button onClick={zoomOut} title="Zoom out" style={{ width: 34, height: 34, border: 0, background: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon name="minus" size={16} color="#4a504a" />
            </button>
          </div>

          {/* annotation: auto-clustering is a Claude Code build item */}
          {showClusters && (
            <div style={{ position: "absolute", left: 14, bottom: 14, maxWidth: 300, display: "flex", alignItems: "flex-start", gap: 8, pointerEvents: "auto",
              background: "rgba(255,255,255,.96)", borderRadius: 8, padding: "9px 11px", boxShadow: "0 2px 10px rgba(0,0,0,.16)", border: "1px solid #e7e5df" }}>
              <Icon name="info" size={14} color="#006747" style={{ marginTop: 1, flex: "none" }} />
              <span style={{ fontSize: 11, lineHeight: 1.45, color: "#4a504a" }}>
                Listings <strong style={{ fontWeight: 600, color: "#1d241f" }}>auto-cluster</strong> when zoomed out and resolve to individual pins as you zoom in. Cluster math &amp; map-synced positioning are wired in Claude Code.
              </span>
            </div>
          )}

          {/* Draw area (bottom-right) */}
          <div style={{ position: "absolute", right: 14, bottom: 14, display: "flex", gap: 8, alignItems: "center", pointerEvents: "auto" }}>
            <button style={{ display: "inline-flex", alignItems: "center", gap: 7, background: "#fff", border: 0, borderRadius: 7, padding: "9px 13px", fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "#006747", cursor: "pointer", boxShadow: "0 2px 8px rgba(0,0,0,.18)" }}>
              <Icon name="pencil" size={14} color="#006747" /> Draw area
            </button>
          </div>

        </div>
      </LocalLogicMap>
    );
  };

  // ---- shared header (client context + filters) ----
  const TopBar = () => (
    <div style={{ flex: "none", borderBottom: "1px solid #ececec", background: "#fff" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "11px 20px", flexWrap: "wrap" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11 }}>
          <div style={{ width: 30, height: 30, borderRadius: "50%", background: "#006747", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12, fontWeight: 600 }}>RF</div>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600, color: "#1d241f" }}>Searching for the Reyes family</div>
            <div style={{ fontSize: 12, color: "#8a8e88" }}>Saved search · alerts on · 6 of 41 listings</div>
          </div>
        </div>
        <div style={{ display: "flex", gap: 9 }}>
          <button style={btnOutline}><Icon name="bell" size={14} color="#006747" /> Save Search</button>
          <button style={btnPrimary}><Icon name="send" size={14} color="#fff" /> Share With Client</button>
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "0 20px 12px", flexWrap: "wrap" }}>
        {filters.map((fl, i) => (
          <button key={i} style={{ display: "inline-flex", alignItems: "center", gap: 7, background: "#f4f3ef", border: "1px solid #e7e5df", borderRadius: 7, padding: "8px 12px", fontFamily: "inherit", fontSize: 13, fontWeight: 500, color: "#1d241f", cursor: "pointer" }}>
            <Icon name={fl.icon} size={14} color="#8a8e88" /> {fl.label} <Icon name="chevron-down" size={13} color="#a8aca6" />
          </button>
        ))}
        <button style={{ display: "inline-flex", alignItems: "center", gap: 7, background: "#fff", border: "1px solid #e7e5df", borderRadius: 7, padding: "8px 12px", fontFamily: "inherit", fontSize: 13, fontWeight: 600, color: "#006747", cursor: "pointer" }}>
          <Icon name="sliders-horizontal" size={14} color="#006747" /> All filters
        </button>
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 12.5, color: "#8a8e88" }}>Sort:</span>
        <button style={{ display: "inline-flex", alignItems: "center", gap: 6, background: "transparent", border: 0, fontFamily: "inherit", fontSize: 13, fontWeight: 600, color: "#1d241f", cursor: "pointer" }}>Best match <Icon name="chevron-down" size={13} color="#a8aca6" /></button>
      </div>
    </div>
  );

  // ===== layouts =====
  if (layout === "gallery") {
    return (
      <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
        <TopBar />
        <div style={{ flex: 1, overflowY: "auto", padding: "18px 20px", background: "#f4f3ef" }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(248px, 1fr))", gap: 16, maxWidth: 1180, margin: "0 auto" }}>
            {results.map((r) => <ResultCard key={r.id} r={r} />)}
          </div>
        </div>
      </div>
    );
  }

  if (layout === "mapDrawer") {
    return (
      <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
        <TopBar />
        <div style={{ flex: 1, position: "relative", minHeight: 0 }}>
          <MapCanvas />
          <div style={{ position: "absolute", top: 16, left: 16, bottom: 16, width: 340, background: "rgba(255,255,255,.97)", borderRadius: 8, boxShadow: "0 6px 24px rgba(0,0,0,.16)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
            <div style={{ padding: "12px 14px", borderBottom: "1px solid #f1f0ea", fontSize: 13, fontWeight: 600, color: "#1d241f" }}>{results.length} homes in view</div>
            <div style={{ flex: 1, overflowY: "auto", padding: 12, display: "flex", flexDirection: "column", gap: 10 }}>
              {results.map((r) => <ResultCard key={r.id} r={r} compact />)}
            </div>
          </div>
        </div>
      </div>
    );
  }

  // default: split
  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
      <TopBar />
      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "minmax(420px, 1.05fr) 1.35fr", minHeight: 0 }}>
        <div style={{ overflowY: "auto", padding: "16px 18px", background: "#f4f3ef", borderRight: "1px solid #ececec" }}>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 14 }}>
            {results.map((r) => <ResultCard key={r.id} r={r} />)}
          </div>
        </div>
        <div style={{ minHeight: 0 }}><MapCanvas /></div>
      </div>
    </div>
  );
}

window.BuyerSearch = BuyerSearch;
