// Recursive MLS — Screen: My Listings (agent-facing).
// The agent's own listings with live compliance status + a read-only compliance
// issues list (fixes, no fines — fines are admin-only). Edit routes to the editor.
function MyListings({ go }) {
  const D = window.RC_DATA;
  const listings = D.myListings;
  // per-listing agent-facing compliance issues (read-only; fines are NOT shown to agents)
  const ISSUES = {
    "RC-4821": [
      { sev: "high", title: "Status change not reported", area: "Status", fix: "This home went under contract 3 days ago — update the MLS status within 24 hours to stay compliant.", code: "STATUS-03" },
      { sev: "low", title: "Year built missing", area: "Data", fix: "Add the year built — it’s used in buyer search filters.", code: "PRICE-01" },
    ],
    "RC-4790": [],
    "RC-4755": [
      { sev: "medium", title: "Branded info in photo", area: "Media", fix: "Photo 3 shows a brokerage phone number overlay — replace it with a clean image.", code: "WTRMK-01" },
    ],
    "RC-4702": [
      { sev: "medium", title: "Only 6 photos", area: "Media", fix: "Add at least 10 photos — listings with 10+ get up to 7× more inquiries.", code: "PHOTO-01" },
      { sev: "low", title: "No virtual tour", area: "Media", fix: "Add a 3D or video walkthrough to lift views.", code: "PHOTO-02" },
    ],
  };
  const sevColor = { high: { c: "#b3261e", b: "#fbe9e7" }, medium: { c: "#9a6a12", b: "#fbf2dc" }, low: { c: "#6b706a", b: "#f0efe9" } };
  const statusColor = { Active: { c: "#1f8a5b", b: "#e8f4ee" }, Pending: { c: "#9a6a12", b: "#fbf2dc" }, "Price drop": { c: "#c0612f", b: "#faece3" } };

  const [sel, setSel] = useState(listings[0].id);
  const selL = listings.find((l) => l.id === sel) || listings[0];
  const selIssues = ISSUES[sel] || [];
  const issueCount = (id) => (ISSUES[id] || []).length;
  const topSev = (id) => { const is = ISSUES[id] || []; if (is.some((x) => x.sev === "high")) return "high"; if (is.some((x) => x.sev === "medium")) return "medium"; if (is.length) return "low"; return null; };
  const totalOpen = listings.reduce((s, l) => s + issueCount(l.id), 0);

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
      <div style={{ flex: "none", padding: "22px 28px 0", display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 14, flexWrap: "wrap" }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 25, fontWeight: 600, letterSpacing: "-0.6px", color: "#1d241f" }}>My listings</h1>
          <p style={{ margin: "5px 0 0", fontSize: 14, color: "#8a8e88" }}>{listings.length} listings · <span style={{ color: totalOpen ? "#c0612f" : "#1f8a5b", fontWeight: 600 }}>{totalOpen} compliance {totalOpen === 1 ? "item" : "items"} to resolve</span></p>
        </div>
        <button onClick={() => go && go("listing")} style={btnPrimary}><Icon name="plus" size={15} color="#fff" /> Add Listing</button>
      </div>

      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "minmax(380px, 0.95fr) 1.4fr", minHeight: 0, padding: "16px 28px 28px" }}>
        {/* listing list */}
        <div style={{ display: "flex", flexDirection: "column", minHeight: 0, background: "#fff", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", borderRadius: "3px 0 0 3px", overflowY: "auto" }}>
          {listings.map((l) => {
            const on = l.id === sel; const ts = topSev(l.id); const n = issueCount(l.id);
            return (
              <div key={l.id} onClick={() => setSel(l.id)} className="rc-row" style={{ display: "flex", gap: 12, padding: "13px 15px", cursor: "pointer", borderBottom: "1px solid #f6f5f0", background: on ? "#f3f6f4" : "transparent", borderLeft: on ? "2.5px solid #006747" : "2.5px solid transparent" }}>
                <div style={{ width: 64, height: 64, borderRadius: 6, backgroundImage: `url(${l.photo})`, backgroundSize: "cover", backgroundPosition: "center", flex: "none" }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{l.addr}</div>
                  <div style={{ fontSize: 11.5, color: "#8a8e88", marginTop: 1 }}>{l.city}</div>
                  <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 7 }}>
                    <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 13, fontWeight: 700, color: "#1d241f" }}>{D.usd(l.price)}</span>
                    <span style={{ fontSize: 10.5, fontWeight: 600, color: (statusColor[l.status] || {}).c, background: (statusColor[l.status] || {}).b, borderRadius: 999, padding: "2px 8px" }}>{l.status}</span>
                  </div>
                </div>
                <div style={{ flex: "none", display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 4 }}>
                  {ts
                    ? <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 11, fontWeight: 600, color: sevColor[ts].c, background: sevColor[ts].b, borderRadius: 999, padding: "2px 9px" }}><Icon name="shield-alert" size={12} color={sevColor[ts].c} /> {n}</span>
                    : <span style={{ display: "inline-flex", alignItems: "center", gap: 4, fontSize: 11, fontWeight: 600, color: "#1f8a5b", background: "#e8f4ee", borderRadius: 999, padding: "2px 9px" }}><Icon name="shield-check" size={12} color="#1f8a5b" /> Clear</span>}
                  <span style={{ fontSize: 11, color: "#bcbfba" }}>{l.dom}d · {l.views.toLocaleString()} views</span>
                </div>
              </div>
            );
          })}
        </div>

        {/* detail: compliance (read-only) + edit */}
        <div style={{ minHeight: 0, background: "#fbfaf7", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", borderRadius: "0 3px 3px 0", overflowY: "auto" }}>
          <div style={{ position: "relative", height: 150, backgroundImage: `linear-gradient(180deg, rgba(0,0,0,0) 40%, rgba(0,0,0,.55)), url(${selL.photo})`, backgroundSize: "cover", backgroundPosition: "center", borderRadius: "0 3px 0 0" }}>
            <div style={{ position: "absolute", left: 20, bottom: 14, right: 20, display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 12 }}>
              <div>
                <div style={{ fontSize: 18, fontWeight: 600, color: "#fff" }}>{selL.addr}</div>
                <div style={{ fontSize: 12.5, color: "rgba(255,255,255,.85)", marginTop: 2 }}>{selL.city} · {selL.beds}bd · {selL.baths}ba · {selL.sqft.toLocaleString()} sqft</div>
              </div>
              <button onClick={() => go && go("listing")} style={{ ...btnPrimary, padding: "8px 14px", flex: "none" }}><Icon name="pencil" size={14} color="#fff" /> Edit Listing</button>
            </div>
          </div>

          <div style={{ padding: 20 }}>
            {/* performance strip */}
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10, marginBottom: 18 }}>
              {[["Price", D.usd(selL.price)], ["Days on mkt", selL.dom], ["Views", selL.views.toLocaleString()], ["Showings", selL.showings]].map(([k, v]) => (
                <div key={k} style={{ background: "#fff", borderRadius: 8, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "10px 12px" }}>
                  <div style={{ fontSize: 10, color: "#8a8e88", textTransform: "uppercase", letterSpacing: ".5px" }}>{k}</div>
                  <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 15, fontWeight: 700, color: "#1d241f", marginTop: 3 }}>{v}</div>
                </div>
              ))}
            </div>

            {/* compliance — read-only for the agent (fixes, no fines) */}
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 10 }}>
              <h3 style={{ margin: 0, fontSize: 15, fontWeight: 600, color: "#1d241f", display: "flex", alignItems: "center", gap: 8 }}>
                <Icon name="shield-check" size={17} color="#006747" /> Compliance
              </h3>
              {selIssues.length === 0
                ? <span style={{ fontSize: 11.5, fontWeight: 600, color: "#1f8a5b", background: "#e8f4ee", borderRadius: 999, padding: "3px 10px" }}>All clear</span>
                : <span style={{ fontSize: 11.5, fontWeight: 600, color: "#c0612f", background: "#faece3", borderRadius: 999, padding: "3px 10px" }}>{selIssues.length} to resolve</span>}
            </div>

            {selIssues.length === 0 ? (
              <div style={{ background: "#fff", borderRadius: 8, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "20px", textAlign: "center" }}>
                <Icon name="shield-check" size={26} color="#1f8a5b" />
                <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", marginTop: 8 }}>This listing is fully compliant</div>
                <div style={{ fontSize: 12.5, color: "#8a8e88", marginTop: 3 }}>No open issues. Keep status and media current to stay clear.</div>
              </div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
                {selIssues.map((iss, i) => (
                  <div key={i} style={{ background: "#fff", borderRadius: 8, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "13px 15px" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 6 }}>
                      <span style={{ fontSize: 10.5, fontWeight: 600, color: sevColor[iss.sev].c, background: sevColor[iss.sev].b, borderRadius: 999, padding: "2px 8px", textTransform: "capitalize" }}>{iss.sev}</span>
                      <span style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", flex: 1 }}>{iss.title}</span>
                      <span style={{ fontSize: 10.5, color: "#bcbfba", fontFamily: "'Space Mono', monospace" }}>{iss.code}</span>
                    </div>
                    <div style={{ fontSize: 12.5, color: "#6b706a", lineHeight: 1.5, marginBottom: 11 }}>{iss.fix}</div>
                    <button onClick={() => go && go("listing")} style={{ ...btnOutline, padding: "6px 12px", fontSize: 12.5 }}><Icon name="pencil" size={13} color="#006747" /> Fix in listing</button>
                  </div>
                ))}
                <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 11.5, color: "#a8aca6", marginTop: 4 }}>
                  <Icon name="info" size={13} color="#a8aca6" />
                  <span>Resolve issues by editing the listing. Any fines are managed by MLS administration — you’ll be notified if one applies.</span>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.MyListings = MyListings;
