// Recursive MLS — Consumer: public home portal (OneHome-style).
// The per-MLS public search site connected to the agent who sent the alert.
// Clicking a home in the email lands here. Consumer-facing, no agent chrome.
function ConsumerPortal() {
  const D = window.RC_DATA;
  const homes = D.searchResults;
  const agent = { name: "Alex Morgan", brokerage: "Recursive Realty", phone: "(305) 555-0148", initials: "AM" };
  const [favs, setFavs] = useState({ "S-1": true });
  const [tab, setTab] = useState("recommended");
  const [viewing, setViewing] = useState(null);
  const toggleFav = (id) => setFavs({ ...favs, [id]: !favs[id] });
  const match = (i) => [98, 95, 91, 88, 84, 80][i] || 78;

  if (viewing) return <ConsumerProperty home={viewing} onBack={() => setViewing(null)} fav={favs[viewing.id]} onFav={() => toggleFav(viewing.id)} />;

  return (
    <div style={{ minHeight: "100vh", background: "#faf9f5", fontFamily: "'Space Grotesk', -apple-system, system-ui, sans-serif" }}>
      {/* top bar */}
      <div style={{ position: "sticky", top: 0, zIndex: 10, background: "#fff", borderBottom: "1px solid #ece9e0", display: "flex", alignItems: "center", gap: 16, padding: "0 28px", height: 62 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
          <svg width="28" height="28" viewBox="0 0 100 100"><rect x="13" y="13" width="74" height="74" rx="2" fill="none" stroke="#006747" strokeWidth="7" /><g transform="translate(50,50) scale(0.62) translate(-50,-52)"><path d="M18 80 A8 8 0 0 1 34 80 A8 8 0 0 1 50 80 A8 8 0 0 1 66 80 A8 8 0 0 1 82 80 M26 64 A8 8 0 0 1 42 64 A8 8 0 0 1 58 64 A8 8 0 0 1 74 64 M34 48 A8 8 0 0 1 50 48 A8 8 0 0 1 66 48 M42 32 A8 8 0 0 1 58 32" fill="none" stroke="#006747" strokeWidth="8" strokeLinecap="round" /></g></svg>
          <span style={{ fontSize: 17, fontWeight: 600, color: "#1d241f", letterSpacing: "-0.3px" }}>Recursive<span style={{ color: "#8a8e88", fontWeight: 400 }}> Homes</span></span>
        </div>
        <div style={{ flex: 1, maxWidth: 420, display: "flex", alignItems: "center", gap: 8, background: "#f4f3ef", borderRadius: 9, padding: "9px 13px" }}>
          <Icon name="search" size={15} color="#a8aca6" />
          <input placeholder="City, neighborhood, or ZIP" defaultValue="Central Austin" style={{ flex: 1, border: 0, outline: 0, background: "transparent", fontFamily: "inherit", fontSize: 13.5 }} />
        </div>
        <div style={{ flex: 1 }} />
        <button style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "inherit", fontSize: 13, fontWeight: 600, color: "#006747", background: "none", border: 0, cursor: "pointer" }}><Icon name="heart" size={16} color="#006747" /> Favorites</button>
        <span style={{ width: 34, height: 34, borderRadius: "50%", background: "#006747", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 600, fontSize: 13 }}>JR</span>
      </div>

      {/* hero — you + your agent */}
      <div style={{ background: "linear-gradient(120deg, #006747 0%, #0a5740 100%)", color: "#fff", padding: "30px 28px" }}>
        <div style={{ maxWidth: 1200, margin: "0 auto", display: "flex", alignItems: "center", justifyContent: "space-between", gap: 20, flexWrap: "wrap" }}>
          <div>
            <div style={{ fontSize: 12, fontWeight: 600, letterSpacing: "1.2px", textTransform: "uppercase", opacity: 0.75 }}>Welcome back, Jordan</div>
            <h1 style={{ margin: "8px 0 6px", fontSize: 27, fontWeight: 600, letterSpacing: "-0.7px" }}>Homes picked for you</h1>
            <p style={{ margin: 0, fontSize: 14, opacity: 0.85, maxWidth: 520, lineHeight: 1.5 }}>Curated from your saved search with {agent.name}. Heart the ones you love — your agent sees them instantly.</p>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 12, background: "rgba(255,255,255,.12)", borderRadius: 12, padding: "13px 16px" }}>
            <span style={{ width: 44, height: 44, borderRadius: "50%", background: "#fff", color: "#006747", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 600, fontSize: 15, flex: "none" }}>{agent.initials}</span>
            <div>
              <div style={{ fontSize: 11, opacity: 0.75 }}>Your agent</div>
              <div style={{ fontSize: 14.5, fontWeight: 600 }}>{agent.name}</div>
              <div style={{ fontSize: 12, opacity: 0.8 }}>{agent.brokerage}</div>
            </div>
            <button style={{ fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, cursor: "pointer", border: 0, borderRadius: 8, padding: "8px 13px", background: "#fff", color: "#006747", marginLeft: 4 }}>Contact</button>
          </div>
        </div>
      </div>

      {/* saved-search summary + tabs */}
      <div style={{ maxWidth: 1200, margin: "0 auto", padding: "20px 28px 0" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap", marginBottom: 16 }}>
          <span style={{ fontSize: 12.5, fontWeight: 600, color: "#8a8e88" }}>Your search:</span>
          {["Central Austin", "3+ beds", "Under $950K", "Single family"].map((c) => (
            <span key={c} style={{ fontSize: 12.5, color: "#006747", background: "#eef4f1", borderRadius: 999, padding: "5px 12px", fontWeight: 600 }}>{c}</span>
          ))}
          <button style={{ fontSize: 12.5, fontWeight: 600, color: "#8a8e88", background: "none", border: 0, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="sliders-horizontal" size={13} color="#8a8e88" /> Edit</button>
        </div>
        <div style={{ display: "flex", gap: 4, borderBottom: "1px solid #ece9e0" }}>
          {[["recommended", "Recommended", homes.length], ["favorites", "Favorites", Object.values(favs).filter(Boolean).length], ["map", "Map", null]].map(([id, lab, n]) => (
            <button key={id} onClick={() => setTab(id)} style={{ display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "inherit", fontSize: 13.5, fontWeight: 600, cursor: "pointer", border: 0, background: "transparent", padding: "10px 14px", color: tab === id ? "#006747" : "#8a8e88", borderBottom: tab === id ? "2px solid #006747" : "2px solid transparent", marginBottom: -1 }}>
              {lab}{n != null && <span style={{ fontSize: 11, color: "#a8aca6" }}>{n}</span>}
            </button>
          ))}
        </div>
      </div>

      {/* body */}
      <div style={{ maxWidth: 1200, margin: "0 auto", padding: "20px 28px 60px", display: "grid", gridTemplateColumns: "1fr 300px", gap: 24, alignItems: "start" }}>
        <div>
          {tab === "map" ? (
            <ConsumerMap homes={homes} D={D} />
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
              {(tab === "favorites" ? homes.filter((h) => favs[h.id]) : homes).map((h, i) => (
                <div key={h.id} style={{ background: "#fff", borderRadius: 12, overflow: "hidden", boxShadow: "0 1px 3px rgba(0,0,0,.08), inset 0 0 0 1px rgba(0,0,0,.05)", cursor: "pointer" }} onClick={() => setViewing(h)}>
                  <div style={{ position: "relative", height: 178, backgroundImage: `url(${h.photos[0]})`, backgroundSize: "cover", backgroundPosition: "center" }}>
                    <span style={{ position: "absolute", top: 11, left: 11, fontSize: 11, fontWeight: 700, color: "#006747", background: "rgba(255,255,255,.92)", borderRadius: 999, padding: "3px 10px", display: "inline-flex", alignItems: "center", gap: 4 }}><Icon name="sparkles" size={11} color="#006747" /> {match(i)}% match</span>
                    <button onClick={(e) => { e.stopPropagation(); toggleFav(h.id); }} style={{ position: "absolute", top: 9, right: 9, width: 34, height: 34, borderRadius: "50%", border: 0, cursor: "pointer", background: "rgba(255,255,255,.92)", display: "flex", alignItems: "center", justifyContent: "center" }}>
                      <Icon name="heart" size={17} color={favs[h.id] ? "#c0612f" : "#a8aca6"} style={favs[h.id] ? { fill: "#c0612f" } : {}} />
                    </button>
                  </div>
                  <div style={{ padding: "13px 15px" }}>
                    <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
                      <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 18, fontWeight: 700, color: "#1d241f", letterSpacing: "-0.5px" }}>{D.usd(h.price)}</span>
                      <span style={{ fontSize: 11.5, color: "#8a8e88" }}>{h.status}</span>
                    </div>
                    <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", marginTop: 4 }}>{h.addr}</div>
                    <div style={{ fontSize: 12, color: "#8a8e88", marginTop: 1 }}>{h.city}</div>
                    <div style={{ display: "flex", gap: 13, marginTop: 9, fontSize: 12, color: "#4a504a" }}>
                      <span>{h.beds} bd</span><span style={{ color: "#dcdad1" }}>·</span><span>{h.baths} ba</span><span style={{ color: "#dcdad1" }}>·</span><span>{h.sqft.toLocaleString()} sqft</span>
                    </div>
                    <button onClick={(e) => { e.stopPropagation(); setViewing(h); }} style={{ width: "100%", marginTop: 12, fontFamily: "inherit", fontSize: 13, fontWeight: 600, cursor: "pointer", borderRadius: 8, padding: "9px", border: "1px solid #d7ddd9", background: "#fff", color: "#006747" }}>View home</button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* right rail */}
        <div style={{ position: "sticky", top: 78, display: "flex", flexDirection: "column", gap: 16 }}>
          {/* agent */}
          <div style={{ background: "#fff", borderRadius: 12, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: 18, textAlign: "center" }}>
            <span style={{ width: 60, height: 60, borderRadius: "50%", background: "#006747", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 600, fontSize: 21, marginBottom: 10 }}>{agent.initials}</span>
            <div style={{ fontSize: 15.5, fontWeight: 600, color: "#1d241f" }}>{agent.name}</div>
            <div style={{ fontSize: 12.5, color: "#8a8e88", marginTop: 2 }}>{agent.brokerage}</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 14 }}>
              <button style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 7, fontFamily: "inherit", fontSize: 13, fontWeight: 600, cursor: "pointer", borderRadius: 8, padding: "10px", border: 0, background: "#006747", color: "#fff" }}><Icon name="message-circle" size={15} color="#fff" /> Message {agent.name.split(" ")[0]}</button>
              <button style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 7, fontFamily: "inherit", fontSize: 13, fontWeight: 600, cursor: "pointer", borderRadius: 8, padding: "10px", border: "1px solid #d7ddd9", background: "#fff", color: "#006747" }}><Icon name="calendar" size={15} color="#006747" /> Request a tour</button>
            </div>
          </div>

          {/* market snapshot */}
          <div style={{ background: "#fff", borderRadius: 12, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: 18 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f", marginBottom: 12 }}>Central Austin market</div>
            {[["Median price", "$612K", "+3.1%"], ["Days on market", "29", "−4d"], ["Homes for sale", "1,284", "+112"]].map(([k, v, d]) => (
              <div key={k} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "7px 0", borderBottom: "1px solid #f6f5f0" }}>
                <span style={{ fontSize: 12.5, color: "#8a8e88" }}>{k}</span>
                <span style={{ fontSize: 13, fontWeight: 600, color: "#1d241f", fontFamily: "'Space Mono', monospace" }}>{v} <span style={{ fontSize: 11, color: "#1f8a5b" }}>{d}</span></span>
              </div>
            ))}
            <div style={{ fontSize: 11, color: "#a8aca6", marginTop: 10 }}>Updated today · powered by your agent's Market Insights</div>
          </div>
        </div>
      </div>
    </div>
  );
}

// simple consumer map (Leaflet if available, else stylized)
function ConsumerMap({ homes, D }) {
  const ref = React.useRef(null);
  const mapRef = React.useRef(null);
  React.useEffect(() => {
    if (!window.L || !ref.current || mapRef.current) return;
    const coords = homes.map((h, i) => [30.27 + (i - 2) * 0.02, -97.74 + (i - 2) * 0.025]);
    mapRef.current = window.L.map(ref.current, { zoomControl: true, scrollWheelZoom: false });
    window.L.tileLayer("https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png", { maxZoom: 19, attribution: "© OpenStreetMap, © CARTO" }).addTo(mapRef.current);
    homes.forEach((h, i) => {
      const icon = window.L.divIcon({ className: "", html: `<div style="background:#006747;color:#fff;font:700 11px 'Space Grotesk',sans-serif;padding:4px 8px;border-radius:999px;box-shadow:0 2px 6px rgba(0,0,0,.3);white-space:nowrap">$${Math.round(h.price/1000)}K</div>`, iconSize: [50, 22], iconAnchor: [25, 11] });
      window.L.marker(coords[i], { icon }).addTo(mapRef.current).bindTooltip(h.addr, { direction: "top" });
    });
    mapRef.current.fitBounds(window.L.latLngBounds(coords).pad(0.3));
    setTimeout(() => mapRef.current && mapRef.current.invalidateSize(), 120);
  }, []);
  React.useEffect(() => () => { if (mapRef.current) { mapRef.current.remove(); mapRef.current = null; } }, []);
  return <div ref={ref} style={{ height: 560, borderRadius: 12, overflow: "hidden", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.1)", background: "#eef1ee" }} />;
}

window.ConsumerPortal = ConsumerPortal;
