// Recursive MLS — Screen: Listing Detail (agent-facing, post-publish).
// Opened when an agent clicks a listing from Find Homes. Renders inside the agent
// chrome. Carries the full MLS record PLUS agent-only data (showing instructions,
// lockbox, compensation), the Local Logic neighborhood map, and local demographics.
//
// DATA SOURCES (all included in the platform or free — no added per-listing fees):
//   • MLS data feed (RESO)              — listing facts, history, agent/compensation
//   • County public records (free)      — tax / assessment
//   • Local Logic (already licensed)    — neighborhood map, amenities, transit, schools
//   • U.S. Census ACS (free, public)    — local demographics (income/population/etc.)
//   • FEMA National Flood Hazard (free) — flood-zone risk
//   • NCES / GreatSchools-free tier     — public school directory (ratings via Local Logic)
function ListingDetail({ home, go, onBack }) {
  const D = window.RC_DATA;
  const h = home || D.searchResults[0];
  const geo = h.geo || { lat: 30.2849, lng: -97.7341 };
  const [shot, setShot] = useState(0);
  const [demoTab, setDemoTab] = useState("income");

  const ppsf = Math.round(h.price / h.sqft);
  const mlsNo = "A11" + h.id.replace(/\D/g, "") + "302";

  // ---- Partner deep links (MLS-configurable; 4–6 typical). Each opens the partner
  // system pre-loaded with THIS listing. Logos are standardized to one muted treatment
  // (uniform monogram chip) so no single partner brand dominates the page. ----
  const partners = [
    { id: "rpr", name: "RPR", icon: "bar-chart-3" },
    { id: "cloudcma", name: "Cloud CMA", icon: "cloud" },
    { id: "realist", name: "Realist Tax", icon: "receipt" },
    { id: "forewarn", name: "ForeWarn", icon: "shield-check" },
    { id: "dpr", name: "Down Payment Resource", icon: "piggy-bank" },
  ];
  const orig = Math.round(h.price * 1.035 / 1000) * 1000;
  const tax = Math.round(h.price * 0.0185);
  const assessed = Math.round(h.price * 0.92 / 1000) * 1000;

  // ---- MLS facts ----
  const facts = [
    ["Bedrooms", h.beds], ["Bathrooms", h.baths], ["Living area", h.sqft.toLocaleString() + " sqft"],
    ["$/sqft", "$" + ppsf], ["Property type", h.type], ["Year built", "2019"],
    ["Lot size", "0.21 ac · 9,148 sqft"], ["Garage", "2-car attached"], ["HOA", "$0 / mo"],
    ["Heating / cooling", "Central · electric"], ["Parcel ID", "0214-0908-0021"], ["County", "Travis"],
  ];

  // ---- agent-only ----
  const showing = [
    ["Listing agent", "Alex Morgan · #SL3284417"],
    ["Co-list agent", "—"],
    ["Brokerage", "Recursive Realty · (305) 555-0148"],
    ["Showing service", "Recursive Showings · online booking"],
    ["Lockbox", "SentriLock · front door · code on confirm"],
    ["Occupancy", "Owner-occupied · 24h notice"],
    ["Showing notes", "Park in driveway. Dog crated. Lights on by request."],
  ];

  // ---- listing history (MLS) ----
  const history = [
    { date: "Jun 18, 2026", event: "Listed for sale", price: D.usd(h.price), tone: "active" },
    { date: "Jun 17, 2026", event: "Price adjusted", price: D.usd(h.price) + " (from " + D.usd(orig) + ")", tone: "drop" },
    { date: "Jun 02, 2026", event: "Coming soon", price: D.usd(orig), tone: "muted" },
    { date: "2019", event: "Sold", price: D.usd(Math.round(h.price * 0.62 / 1000) * 1000), tone: "muted" },
  ];

  // ---- parcel history (county records, parcel-centric) — every prior listing of THIS parcel ----
  const parcelHistory = [
    { year: "2026", mls: mlsNo, event: "Active (this listing)", price: D.usd(h.price), agent: "Alex Morgan · Recursive", current: true },
    { year: "2019", mls: "A0982140", event: "Sold", price: D.usd(Math.round(h.price * 0.62 / 1000) * 1000), agent: "J. Okafor · Keller Williams" },
    { year: "2014", mls: "A0561883", event: "Sold", price: D.usd(Math.round(h.price * 0.41 / 1000) * 1000), agent: "M. Devlin · Compass" },
    { year: "2008", mls: "A0228815", event: "Expired", price: D.usd(Math.round(h.price * 0.36 / 1000) * 1000), agent: "R. Salas · Realty Co." },
  ];

  // ---- price timeline points (for the full-width chart over listing history) ----
  const timeline = [
    { t: "2014", label: "Sold", v: Math.round(h.price * 0.41), tone: "muted" },
    { t: "2019", label: "Sold", v: Math.round(h.price * 0.62), tone: "muted" },
    { t: "Jun 2", label: "Coming soon", v: orig, tone: "muted" },
    { t: "Jun 17", label: "Price ↓", v: h.price, tone: "drop" },
    { t: "Jun 18", label: "Listed", v: h.price, tone: "active" },
  ];
  const tVals = timeline.map((p) => p.v);
  const tMin = Math.min(...tVals), tMax = Math.max(...tVals);
  const toneColor = (tn) => (tn === "active" ? "#1f8a5b" : tn === "drop" ? "#c0612f" : "#bcbfba");
  const tPt = (p, i) => ({
    x: timeline.length > 1 ? (i / (timeline.length - 1)) * 100 : 50,
    y: tMax > tMin ? 70 - ((p.v - tMin) / (tMax - tMin)) * 52 : 42,
  });

  // ---- agent performance for this listing ----
  const perf = [["Views", "1,284"], ["Saves", "47"], ["Showings", "9"], ["Days on market", h.dom]];

  // ---- LOCAL DEMOGRAPHICS — U.S. Census ACS (free). Tract around the property. ----
  const DEMO = {
    income: {
      summary: [["Income", [["Individual (per capita)", "$44.0k"], ["Household (median)", "$120.3k"]]],
                ["Employment", [["Employed", "99.3%"], ["Unemployed", "0.7%"]]]],
      chartTitle: "Income brackets (%)", max: 30, axis: ["0", "15%", "30%"],
      bars: [["$0 to $9,000", 0.2], ["$10,000 to $19,000", 1.3], ["$20,000 to $34,000", 7.1],
        ["$35,000 to $49,000", 4.2], ["$50,000 to $74,000", 16.2], ["$75,000 to $100,000", 14.7],
        ["$100,000 to $149,000", 23.4], ["$150,000 to $200,000", 5.5], ["$200,000 or more", 27.4]],
    },
    population: {
      summary: [["Population", [["Total", "18,402"], ["Density", "4,210 / sq mi"]]],
                ["Age", [["Median age", "37.4"], ["5-yr growth", "+6.8%"]]]],
      chartTitle: "Age distribution (%)", max: 30, axis: ["0", "15%", "30%"],
      bars: [["Under 18", 19.6], ["18 to 24", 8.1], ["25 to 34", 21.3], ["35 to 44", 17.8],
        ["45 to 54", 12.4], ["55 to 64", 10.9], ["65 and over", 9.9]],
    },
    housing: {
      summary: [["Tenure", [["Owner-occupied", "61.2%"], ["Renter-occupied", "38.8%"]]],
                ["Value", [["Median home value", "$548k"], ["Median rent", "$1,940 / mo"]]]],
      chartTitle: "Units by structure (%)", max: 70, axis: ["0", "35%", "70%"],
      bars: [["Single-family detached", 64.3], ["Townhouse / attached", 9.7],
        ["2 to 9 units", 11.2], ["10 to 49 units", 8.8], ["50+ units", 5.1], ["Other", 0.9]],
    },
    household: {
      summary: [["Households", [["Total", "7,165"], ["Avg. size", "2.5"]]],
                ["Composition", [["Family households", "58.4%"], ["With children", "29.1%"]]]],
      chartTitle: "Household type (%)", max: 45, axis: ["0", "22%", "45%"],
      bars: [["Married, no kids", 28.6], ["Married with kids", 24.2], ["Single parent", 7.5],
        ["Living alone", 27.8], ["Roommates / other", 11.9]],
    },
    education: {
      summary: [["Attainment", [["Bachelor's +", "63.1%"], ["Graduate degree", "27.4%"]]],
                ["Enrollment", [["School-age", "3,120"], ["In college", "2,040"]]]],
      chartTitle: "Educational attainment (%)", max: 40, axis: ["0", "20%", "40%"],
      bars: [["No high school", 3.2], ["High school grad", 12.1], ["Some college", 14.9],
        ["Associate", 6.7], ["Bachelor's", 35.7], ["Graduate / pro", 27.4]],
    },
    commute: {
      summary: [["Commute", [["Mean travel time", "24.6 min"], ["Leave 7–8 AM", "41.2%"]]],
                ["Remote", [["Work from home", "22.8%"], ["No vehicle", "4.1%"]]]],
      chartTitle: "Commute mode (%)", max: 70, axis: ["0", "35%", "70%"],
      bars: [["Drive alone", 62.4], ["Carpool", 8.3], ["Public transit", 3.1],
        ["Walk", 2.9], ["Bike", 1.4], ["Work from home", 22.8]],
    },
  };
  const demo = DEMO[demoTab];
  const demoTabs = [
    ["income", "Income", "wallet"], ["population", "Population", "users"], ["housing", "Housing", "building-2"],
    ["household", "Household", "users-round"], ["education", "Education", "graduation-cap"], ["commute", "Commute", "route"],
  ];

  const sectionLabel = (t) => (
    <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "1.5px", textTransform: "uppercase", color: "#8a8e88", marginBottom: 10 }}>{t}</div>
  );
  const card = { background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)" };
  const src = (t) => <div style={{ fontSize: 10.5, color: "#bcbfba", marginTop: 12 }}>{t}</div>;

  return (
    <div style={{ height: "100%", overflowY: "auto", background: "#f4f3ef" }}>

      {/* action bar */}
      <div style={{ position: "sticky", top: 0, zIndex: 12, background: "#fff", borderBottom: "1px solid #ececec", display: "flex", alignItems: "center", gap: 12, padding: "0 24px", height: 56 }}>
        <button onClick={() => (onBack ? onBack() : go && go("search"))} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "inherit", fontSize: 13.5, fontWeight: 600, color: "#006747", background: "none", border: 0, cursor: "pointer" }}><Icon name="arrow-left" size={16} color="#006747" /> Find homes</button>
        <span style={{ width: 1, height: 22, background: "#ececec" }} />
        <span style={{ fontSize: 12.5, color: "#8a8e88" }}>MLS# {mlsNo} · <span style={{ color: "#1f8a5b", fontWeight: 600 }}>{h.status}</span></span>
        <div style={{ flex: 1 }} />
        <div style={{ display: "flex", gap: 8 }}>
          {[
            ["showings", "calendar-clock", "Showing"],
            ["offers", "file-signature", "Offer"],
            ["inbox", "message-circle", "Message Agent"],
            ["cma", "calculator", "CMA"],
            [null, "share-2", "Share"],
            [null, "printer", "Print"],
          ].map(([dest, icon, label]) => (
            <button key={label} onClick={() => dest && go && go(dest)} style={btnAct}>
              <Icon name={icon} size={15} color="#006747" />
              <span>{label}</span>
            </button>
          ))}
        </div>
      </div>

      <div style={{ maxWidth: 1180, margin: "0 auto", padding: "22px 24px 64px" }}>

        {/* gallery */}
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 9, height: 392 }}>
          <div style={{ borderRadius: 4, backgroundImage: `url(${h.photos[shot]})`, backgroundSize: "cover", backgroundPosition: "center", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.06)" }} />
          <div style={{ display: "grid", gridTemplateRows: "1fr 1fr", gap: 9, minHeight: 0 }}>
            {[1, 2].map((k) => <div key={k} style={{ borderRadius: 4, backgroundImage: `url(${h.photos[k % h.photos.length]})`, backgroundSize: "cover", backgroundPosition: "center", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.06)" }} />)}
          </div>
        </div>
        <div style={{ display: "flex", gap: 8, marginTop: 9 }}>
          {h.photos.map((p, i) => <button key={i} onClick={() => setShot(i)} style={{ width: 60, height: 44, borderRadius: 4, border: i === shot ? "2px solid #006747" : "2px solid transparent", padding: 0, cursor: "pointer", backgroundImage: `url(${p})`, backgroundSize: "cover", backgroundPosition: "center" }} />)}
        </div>

        {/* MLS number + partner deep links */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap", marginTop: 14, padding: "12px 14px", background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <span style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: "1px", textTransform: "uppercase", color: "#8a8e88" }}>MLS number</span>
            <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 18, fontWeight: 700, color: "#1d241f", letterSpacing: "0.5px" }}>{mlsNo}</span>
            <button title="Copy MLS number" style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 26, height: 26, borderRadius: 6, border: "1px solid #e2e0d8", background: "#fff", cursor: "pointer" }}><Icon name="copy" size={13} color="#8a8e88" /></button>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 7, flexWrap: "wrap" }}>
            <span style={{ fontSize: 10.5, fontWeight: 600, letterSpacing: "1px", textTransform: "uppercase", color: "#a8aca6" }}>Open in</span>
            {partners.map((p) => (
              <button key={p.id} title={`Open ${p.name} for this listing`} style={partnerBtn}>
                <Icon name={p.icon} size={16} color="#8a8e88" />
              </button>
            ))}
          </div>
        </div>

        {/* title row */}
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 14, flexWrap: "wrap", margin: "22px 0 4px" }}>
          <div>
            <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 32, fontWeight: 700, color: "#1d241f", letterSpacing: "-1px" }}>{D.usd(h.price)}</div>
            <div style={{ fontSize: 18, fontWeight: 600, color: "#1d241f", marginTop: 5 }}>{h.addr}</div>
            <div style={{ fontSize: 13.5, color: "#8a8e88", marginTop: 2 }}>{h.city}</div>
          </div>
          <div style={{ display: "flex", gap: 20, fontSize: 14.5, color: "#4a504a" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="bed-double" size={18} color="#8a8e88" /> {h.beds} bd</span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="bath" size={18} color="#8a8e88" /> {h.baths} ba</span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="ruler" size={18} color="#8a8e88" /> {h.sqft.toLocaleString()} sqft</span>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="dollar-sign" size={18} color="#8a8e88" /> ${ppsf}/sqft</span>
          </div>
        </div>

        {/* two-col body */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 312px", gap: 26, alignItems: "start", marginTop: 18 }}>

          {/* MAIN */}
          <div>
            {/* about */}
            <div style={{ ...card, padding: 20 }}>
              {sectionLabel("Listing remarks")}
              <p style={{ margin: 0, fontSize: 14, color: "#4a504a", lineHeight: 1.65 }}>Light-filled {h.beds}-bedroom {h.type.toLowerCase()} in {h.city.split(",")[0]} with an open chef's kitchen, white-oak floors, and a wall of glass to a level, fenced backyard. Updated systems, impact windows, and a finished two-car garage. Walkable to parks and dining with quick access to downtown.</p>
            </div>

            {/* facts */}
            <div style={{ marginTop: 18 }}>
              {sectionLabel("Facts & features")}
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 1, background: "#ececec", borderRadius: 3, overflow: "hidden", boxShadow: "inset 0 0 0 1px #ececec" }}>
                {facts.map(([k, v]) => (
                  <div key={k} style={{ background: "#fff", padding: "12px 14px" }}>
                    <div style={{ fontSize: 10.5, color: "#8a8e88", textTransform: "uppercase", letterSpacing: ".5px" }}>{k}</div>
                    <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", marginTop: 3 }}>{v}</div>
                  </div>
                ))}
              </div>
              {src("Source: MLS data feed (RESO)")}
            </div>

            {/* agent-only */}
            <div style={{ marginTop: 18, ...card, padding: 20, boxShadow: "inset 0 0 0 1px #d6e7de", background: "#f3f8f5" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
                <Icon name="lock" size={14} color="#006747" />
                <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: "1.5px", textTransform: "uppercase", color: "#006747" }}>Agent &amp; showing info</span>
                <span style={{ fontSize: 10, fontWeight: 600, letterSpacing: ".4px", textTransform: "uppercase", color: "#006747", background: "#e1efe8", borderRadius: 4, padding: "2px 7px" }}>Agents only</span>
              </div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "11px 22px" }}>
                {showing.map(([k, v]) => (
                  <div key={k}>
                    <div style={{ fontSize: 10.5, color: "#8a8e88", textTransform: "uppercase", letterSpacing: ".5px" }}>{k}</div>
                    <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", marginTop: 2 }}>{v}</div>
                  </div>
                ))}
              </div>
              {src("Source: MLS data feed — restricted fields, not shown on consumer pages")}
            </div>

            {/* price timeline (full width) */}
            <div style={{ marginTop: 18 }}>
              {sectionLabel("Price & status timeline")}
              <div style={{ ...card, padding: "20px 24px 16px" }}>
                <div style={{ position: "relative", width: "100%", height: 150 }}>
                  <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ position: "absolute", inset: 0, width: "100%", height: "100%" }}>
                    <polyline fill="none" stroke="#d2dccf" strokeWidth="2" vectorEffect="non-scaling-stroke"
                      points={timeline.map((p, i) => { const pt = tPt(p, i); return `${pt.x},${pt.y}`; }).join(" ")} />
                  </svg>
                  {timeline.map((p, i) => {
                    const pt = tPt(p, i);
                    return (
                      <div key={i} style={{ position: "absolute", left: `${pt.x}%`, top: `${pt.y}%`, transform: "translate(-50%,-50%)", zIndex: 2 }}>
                        <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 11.5, fontWeight: 700, color: "#1d241f", whiteSpace: "nowrap", textAlign: "center", marginBottom: 6 }}>{D.usd(p.v)}</div>
                        <div style={{ width: 13, height: 13, borderRadius: "50%", background: toneColor(p.tone), border: "2.5px solid #fff", boxShadow: "0 0 0 1px " + toneColor(p.tone), margin: "0 auto" }} />
                      </div>
                    );
                  })}
                  {timeline.map((p, i) => {
                    const pt = tPt(p, i);
                    return (
                      <div key={"l" + i} style={{ position: "absolute", left: `${pt.x}%`, top: "100%", transform: "translateX(-50%)", textAlign: "center", whiteSpace: "nowrap" }}>
                        <div style={{ fontSize: 12, fontWeight: 600, color: "#1d241f" }}>{p.t}</div>
                        <div style={{ fontSize: 11, color: toneColor(p.tone) === "#bcbfba" ? "#a8aca6" : toneColor(p.tone) }}>{p.label}</div>
                      </div>
                    );
                  })}
                </div>
                <div style={{ height: 26 }} />
              </div>
              {src("Source: MLS data feed (RESO) + county records")}
            </div>

            {/* history + parcel history */}
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, marginTop: 18 }}>
              <div>
                {sectionLabel("Listing history")}
                <div style={{ ...card, padding: 6 }}>
                  {history.map((e, i) => (
                    <div key={i} style={{ display: "flex", alignItems: "center", gap: 11, padding: "10px 12px", borderBottom: i < history.length - 1 ? "1px solid #f4f3ee" : "none" }}>
                      <span style={{ width: 8, height: 8, borderRadius: "50%", flex: "none", background: e.tone === "active" ? "#1f8a5b" : e.tone === "drop" ? "#c0612f" : "#bcbfba" }} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f" }}>{e.event}</div>
                        <div style={{ fontSize: 11.5, color: "#a8aca6" }}>{e.date}</div>
                      </div>
                      <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 12.5, color: "#4a504a", textAlign: "right" }}>{e.price}</div>
                    </div>
                  ))}
                </div>
                {src("Source: MLS data feed (RESO)")}
              </div>
              <div>
                <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 10 }}>
                  {sectionLabel("Parcel history")}
                  <span style={{ fontSize: 11, color: "#a8aca6" }}>Parcel 0214-0908-0021</span>
                </div>
                <div style={{ ...card, padding: 6 }}>
                  {parcelHistory.map((e, i) => (
                    <div key={i} style={{ display: "flex", alignItems: "center", gap: 11, padding: "10px 12px", borderBottom: i < parcelHistory.length - 1 ? "1px solid #f4f3ee" : "none" }}>
                      <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 12, fontWeight: 700, color: "#8a8e88", width: 34, flex: "none" }}>{e.year}</span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f" }}>{e.event}</div>
                        <div style={{ fontSize: 11, color: "#a8aca6", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{e.agent}</div>
                      </div>
                      <div style={{ textAlign: "right", flex: "none" }}>
                        <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 12.5, color: "#4a504a" }}>{e.price}</div>
                        {e.current
                          ? <span style={{ fontSize: 10, fontWeight: 600, color: "#1f8a5b" }}>This listing</span>
                          : <span style={{ fontSize: 10.5, fontWeight: 600, color: "#006747", display: "inline-flex", alignItems: "center", gap: 3, cursor: "pointer" }}>MLS# {e.mls} <Icon name="arrow-up-right" size={11} color="#006747" /></span>}
                      </div>
                    </div>
                  ))}
                </div>
                {src("Source: County public records — parcel-centric")}
              </div>
            </div>

            {/* tax & assessment (full width) */}
            <div style={{ marginTop: 18 }}>
              {sectionLabel("Tax & assessment")}
              <div style={{ ...card, padding: "16px 20px" }}>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 1, background: "#ececec", borderRadius: 3, overflow: "hidden", boxShadow: "inset 0 0 0 1px #ececec" }}>
                  {[["Annual property tax", D.usd(tax) + " / yr"], ["Assessed value (2025)", D.usd(assessed)], ["Tax rate", "1.85% effective"], ["Exemptions", "Homestead"]].map(([k, v]) => (
                    <div key={k} style={{ background: "#fff", padding: "14px 16px" }}>
                      <div style={{ fontSize: 10.5, color: "#8a8e88", textTransform: "uppercase", letterSpacing: ".5px" }}>{k}</div>
                      <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 16, fontWeight: 600, color: "#1d241f", marginTop: 4 }}>{v}</div>
                    </div>
                  ))}
                </div>
              </div>
              {src("Source: County public records (free)")}
            </div>

            {/* NEIGHBORHOOD — Local Logic */}
            <div style={{ marginTop: 22 }}>
              <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 12 }}>
                {sectionLabel("Neighborhood")}
                <span style={{ fontSize: 11.5, color: "#a8aca6" }}>Amenities, schools &amp; transit</span>
              </div>
              <div style={{ height: 520, borderRadius: 4, overflow: "hidden", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.1)", background: "#e8ebe5" }}>
                <LocalLogicMap lat={geo.lat} lng={geo.lng} zoom={15} scores={true} marker={{ lat: geo.lat, lng: geo.lng, icon: "house" }} />
              </div>
              {src("Source: Local Logic (licensed) — local-content widget")}
            </div>

            {/* DEMOGRAPHICS — Census ACS */}
            <div style={{ marginTop: 24 }}>
              {sectionLabel("Demographics")}
              <h2 style={{ margin: "0 0 14px", fontSize: 26, fontWeight: 600, letterSpacing: "-0.6px", color: "#1d241f" }}>Local demographics</h2>

              {/* tabs */}
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap", borderBottom: "1px solid #ececec", paddingBottom: 12, marginBottom: 16 }}>
                {demoTabs.map(([id, label, icon]) => {
                  const on = demoTab === id;
                  return (
                    <button key={id} onClick={() => setDemoTab(id)} style={{ display: "inline-flex", flexDirection: "column", alignItems: "center", gap: 5, border: 0, background: "none", cursor: "pointer", padding: "4px 12px", color: on ? "#006747" : "#a8aca6" }}>
                      <Icon name={icon} size={20} color={on ? "#006747" : "#a8aca6"} />
                      <span style={{ fontSize: 12, fontWeight: on ? 600 : 500 }}>{label}</span>
                      <span style={{ height: 2, width: "100%", background: on ? "#006747" : "transparent", borderRadius: 2 }} />
                    </button>
                  );
                })}
              </div>

              {/* content */}
              <div style={{ display: "grid", gridTemplateColumns: "232px 1fr", gap: 16, alignItems: "start" }}>
                <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
                  {demo.summary.map(([title, rows]) => (
                    <div key={title} style={{ background: "#f6f5f1", borderRadius: 3, padding: "16px 16px 18px" }}>
                      <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", marginBottom: 14 }}>{title}</div>
                      {rows.map(([k, v]) => (
                        <div key={k} style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 10 }}>
                          <span style={{ fontSize: 12.5, color: "#6b706a" }}>{k}</span>
                          <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 14, fontWeight: 600, color: "#1d241f" }}>{v}</span>
                        </div>
                      ))}
                    </div>
                  ))}
                </div>

                <div style={{ background: "#f6f5f1", borderRadius: 3, padding: "18px 20px 14px" }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", marginBottom: 16 }}>{demo.chartTitle}</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
                    {demo.bars.map(([label, pct]) => (
                      <div key={label} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <span style={{ width: 124, flex: "none", fontSize: 11, color: "#6b706a", textAlign: "right" }}>{label}</span>
                        <div style={{ flex: 1, display: "flex", alignItems: "center", gap: 7 }}>
                          <div style={{ height: 18, width: `${(pct / demo.max) * 100}%`, background: "#16543a", borderRadius: 2, minWidth: 3 }} />
                          <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 11, color: "#6b706a" }}>{pct}%</span>
                        </div>
                      </div>
                    ))}
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", marginLeft: 134, marginTop: 10, paddingTop: 8, borderTop: "1px solid #e6e4dc" }}>
                    {demo.axis.map((a) => <span key={a} style={{ fontFamily: "'Space Mono', monospace", fontSize: 10, color: "#a8aca6" }}>{a}</span>)}
                  </div>
                </div>
              </div>
              {src("Source: U.S. Census Bureau, American Community Survey 5-year (free, public)")}
            </div>
          </div>

          {/* RIGHT RAIL */}
          <div style={{ position: "sticky", top: 72, display: "flex", flexDirection: "column", gap: 16 }}>
            {/* performance */}
            <div style={{ ...card, padding: 16 }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "1px", textTransform: "uppercase", color: "#8a8e88", marginBottom: 12 }}>This listing</div>
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
                {perf.map(([k, v]) => (
                  <div key={k}>
                    <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 20, fontWeight: 700, color: "#1d241f" }}>{v}</div>
                    <div style={{ fontSize: 10.5, color: "#a8aca6", textTransform: "uppercase", letterSpacing: ".5px", marginTop: 1 }}>{k}</div>
                  </div>
                ))}
              </div>
            </div>

            {/* listing agent */}
            <div style={{ ...card, padding: 16 }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "1px", textTransform: "uppercase", color: "#8a8e88", marginBottom: 12 }}>Listing agent</div>
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <span style={{ width: 46, height: 46, borderRadius: "50%", background: "#006747", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 600, fontSize: 15, flex: "none" }}>AM</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: "#1d241f" }}>Alex Morgan</div>
                  <div style={{ fontSize: 12, color: "#8a8e88" }}>Recursive Realty</div>
                </div>
              </div>
              <button style={{ ...btnGhost, width: "100%", justifyContent: "center", marginTop: 14 }}><Icon name="message-circle" size={15} color="#006747" /> Message agent</button>
            </div>

            {/* comps mini */}
            <div style={{ ...card, padding: 16 }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "1px", textTransform: "uppercase", color: "#8a8e88", marginBottom: 12 }}>Comparable sales</div>
              {[["901 Sevilla Ave", 1520000, 2910], ["1120 Alhambra Cir", 1390000, 2650], ["980 Coral Way", 1440000, 2700]].map(([a, p, s]) => (
                <div key={a} style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", padding: "8px 0", borderBottom: "1px solid #f4f3ee" }}>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600, color: "#1d241f", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a}</div>
                    <div style={{ fontSize: 11, color: "#a8aca6" }}>{s.toLocaleString()} sqft · ${Math.round(p / s)}/sqft</div>
                  </div>
                  <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 12.5, color: "#4a504a", flex: "none", marginLeft: 8 }}>{D.usd(p)}</div>
                </div>
              ))}
              <button onClick={() => go && go("cma")} style={{ ...btnGhost, width: "100%", justifyContent: "center", marginTop: 12 }}><Icon name="calculator" size={15} color="#006747" /> Open full CMA</button>
            </div>

            {/* flood risk */}
            <div style={{ ...card, padding: 16 }}>
              <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "1px", textTransform: "uppercase", color: "#8a8e88", marginBottom: 10 }}>Risk &amp; environment</div>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ width: 34, height: 34, borderRadius: 8, background: "#eef4f1", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="waves" size={17} color="#006747" /></span>
                <div><div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f" }}>Flood zone X</div><div style={{ fontSize: 11.5, color: "#8a8e88" }}>Minimal risk · outside 100-yr floodplain</div></div>
              </div>
              {src("Source: FEMA National Flood Hazard Layer (free)")}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

const btnGhost = { display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "#006747", background: "#fff", border: "1px solid #d7ddd9", borderRadius: 7, padding: "8px 12px", cursor: "pointer" };
// Cohesive action-bar button — uniform width & height across all six.
const btnAct = { display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6, width: 116, height: 38, boxSizing: "border-box", fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "#006747", background: "#fff", border: "1px solid #d7ddd9", borderRadius: 7, cursor: "pointer", whiteSpace: "nowrap" };
const btnPri = { display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "#fff", background: "#006747", border: 0, borderRadius: 7, padding: "9px 14px", cursor: "pointer" };

// Standardized partner deep-link button — icon-only, one fixed square size, muted,
// so the links stay quiet and no partner brand dominates. Name is in the tooltip.
const partnerBtn = { display: "inline-flex", alignItems: "center", justifyContent: "center", width: 30, height: 30, flex: "none", color: "#8a8e88", background: "#fff", border: "1px solid #e7e5df", borderRadius: 6, cursor: "pointer" };

window.ListingDetail = ListingDetail;
