// Recursive MLS — Screen 4: Market Insights.
// Agent dials in focus areas + filters → a customizable chart dashboard,
// an AI ask box, and a client-digest setup. Inspired by Homebot /
// HouseCanary Instant Insights / Altos Research market reports.
function MarketInsights() {
  const M = window.RC_MARKET;
  const CC = window.CHART_COLORS;
  const [areas, setAreas] = useState(M.areas);
  const [primary, setPrimary] = useState("a1");
  const [tf, setTf] = useState("1Y");
  const [ptype, setPtype] = useState("All types");
  const [beds, setBeds] = useState("Any beds");
  const [compare, setCompare] = useState(true);
  const [cmpPeriod, setCmpPeriod] = useState("month");
  const [addOpen, setAddOpen] = useState(false);
  const [custOpen, setCustOpen] = useState(false);
  const [charts, setCharts] = useState({ price: true, supply: true, dom: true, dist: true, gauges: true, ppsf: false });

  const active = areas.filter((a) => a.active);
  const months = M.timeframes.find((t) => t.id === tf).months;
  const data = M.build(primary, months);
  const area = areas.find((a) => a.id === primary) || active[0];
  const b = data.base;

  const last = (arr) => arr[arr.length - 1];
  const first = (arr) => arr[0];
  const pct = (arr) => (((last(arr) - first(arr)) / first(arr)) * 100);
  const fmtMoney = (n) => "$" + Math.round(n).toLocaleString();

  const toggleArea = (id) => setAreas(areas.map((a) => a.id === id ? { ...a, active: !a.active } : a));
  const removeArea = (id) => { setAreas(areas.map((a) => a.id === id ? { ...a, active: false } : a)); if (primary === id) { const n = areas.find((a) => a.active && a.id !== id); if (n) setPrimary(n.id); } };

  const kpis = [
    { label: "Median sale price", val: fmtMoney(last(data.price)), series: data.price, delta: data.yoy.price, pos: true },
    { label: "Median $ / sqft", val: "$" + Math.round(last(data.ppsf)), series: data.ppsf, delta: data.yoy.ppsf, pos: true },
    { label: "Days on market", val: Math.round(last(data.dom)), series: data.dom, delta: data.yoy.dom, pos: false, lowerBetter: true },
    { label: "Months of supply", val: b.moi.toFixed(1), series: data.moi, delta: data.yoy.moi, pos: false, lowerBetter: true, raw: b.moi.toFixed(1) },
    { label: "Sale-to-list", val: last(data.stl).toFixed(1) + "%", series: data.stl, delta: data.yoy.stl, pos: true },
    { label: "Active listings", val: b.active, series: data.newListings, delta: data.yoy.active, pos: true },
  ];

  const ChartCard = ({ id, title, sub, action, children, full }) => charts[id] ? (
    <div style={{ gridColumn: full ? "1 / -1" : "auto", background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "15px 18px 12px", minWidth: 0 }}>
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: 12 }}>
        <div>
          <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600, color: "#1d241f" }}>{title}</h3>
          {sub && <div style={{ fontSize: 11.5, color: "#a8aca6", marginTop: 2 }}>{sub}</div>}
        </div>
        {action}
      </div>
      {children}
    </div>
  ) : null;

  const Legend = ({ items }) => (
    <div style={{ display: "flex", gap: 14, marginTop: 8, flexWrap: "wrap" }}>
      {items.map((it) => (
        <span key={it.label} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11.5, color: "#6b706a" }}>
          <span style={{ width: 12, height: it.dash ? 0 : 9, borderTop: it.dash ? `2px dashed ${it.color}` : "none", background: it.dash ? "none" : it.color, borderRadius: 2 }} />{it.label}
        </span>
      ))}
    </div>
  );

  return (
    <div style={{ padding: "22px 28px 60px", maxWidth: 1340, margin: "0 auto" }}>
      {/* title row */}
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 14, marginBottom: 16 }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 25, fontWeight: 600, letterSpacing: "-0.6px", color: "#1d241f" }}>Market Insights</h1>
          <p style={{ margin: "5px 0 0", fontSize: 14, color: "#8a8e88" }}>Live market analytics for the areas you work — and beautiful updates your clients actually read.</p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button onClick={() => setCustOpen(!custOpen)} style={{ ...btnOutline, position: "relative" }}><Icon name="sliders-horizontal" size={15} color="#006747" /> Customize
            {custOpen && (
              <div onClick={(e) => e.stopPropagation()} style={{ position: "absolute", top: "calc(100% + 8px)", right: 0, width: 230, background: "#fff", borderRadius: 8, boxShadow: "0 8px 28px rgba(0,0,0,.16), inset 0 0 0 1px rgba(0,0,0,.06)", padding: 8, zIndex: 20, textAlign: "left" }}>
                <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: "1px", textTransform: "uppercase", color: "#a8aca6", padding: "6px 8px" }}>Show charts</div>
                {[["price", "Sale price trend"], ["ppsf", "Price per sqft"], ["supply", "New listings vs sold"], ["dom", "Days on market"], ["dist", "Price quartiles"], ["gauges", "Market temperature"]].map(([k, lab]) => (
                  <label key={k} style={{ display: "flex", alignItems: "center", gap: 9, padding: "7px 8px", borderRadius: 6, cursor: "pointer", fontSize: 13, fontWeight: 400, color: "#1d241f" }} className="rc-nav-item">
                    <input type="checkbox" checked={charts[k]} onChange={() => setCharts({ ...charts, [k]: !charts[k] })} style={{ accentColor: "#006747" }} /> {lab}
                  </label>
                ))}
              </div>
            )}
          </button>
          <button style={btnOutline}><Icon name="download" size={15} color="#006747" /> Export</button>
          <button style={btnPrimary}><Icon name="send" size={15} color="#fff" /> Send Update</button>
        </div>
      </div>

      {/* AREA SELECTOR */}
      <div style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "12px 14px", marginBottom: 12 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
          <span style={{ fontSize: 11, fontWeight: 600, textTransform: "uppercase", letterSpacing: ".8px", color: "#a8aca6", flex: "none" }}>Focus areas</span>
          {active.map((a) => {
            const on = primary === a.id;
            return (
              <button key={a.id} onClick={() => setPrimary(a.id)} style={{ display: "inline-flex", alignItems: "center", gap: 8, fontFamily: "inherit", cursor: "pointer",
                padding: "7px 9px 7px 11px", borderRadius: 999, fontSize: 13, fontWeight: 600,
                border: on ? "1px solid #006747" : "1px solid #e2e0d8", background: on ? "#eef4f1" : "#fff", color: on ? "#006747" : "#4a504a" }}>
                <Icon name={M.areaTypeIcon[a.type]} size={14} color={on ? "#006747" : "#8a8e88"} />
                {a.name}
                <span onClick={(e) => { e.stopPropagation(); removeArea(a.id); }} style={{ display: "inline-flex", marginLeft: 1, opacity: 0.5 }}><Icon name="x" size={13} color={on ? "#006747" : "#8a8e88"} /></span>
              </button>
            );
          })}
          <div style={{ position: "relative" }}>
            <button onClick={() => setAddOpen(!addOpen)} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "inherit", cursor: "pointer", padding: "7px 12px", borderRadius: 999, fontSize: 13, fontWeight: 600, border: "1px dashed #c8c6bc", background: "#fff", color: "#006747" }}>
              <Icon name="plus" size={14} color="#006747" /> Add area
            </button>
            {addOpen && (
              <div style={{ position: "absolute", top: "calc(100% + 8px)", left: 0, width: 280, background: "#fff", borderRadius: 8, boxShadow: "0 8px 28px rgba(0,0,0,.16), inset 0 0 0 1px rgba(0,0,0,.06)", padding: 8, zIndex: 20 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, background: "#f4f3ef", borderRadius: 6, padding: "8px 10px", marginBottom: 6 }}>
                  <Icon name="search" size={14} color="#a8aca6" />
                  <input autoFocus placeholder="Neighborhood, ZIP, school district…" style={{ flex: 1, border: 0, background: "transparent", outline: 0, fontFamily: "inherit", fontSize: 13 }} />
                </div>
                {areas.filter((a) => !a.active).map((a) => (
                  <div key={a.id} onClick={() => { toggleArea(a.id); setPrimary(a.id); setAddOpen(false); }} className="rc-nav-item" style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 9px", borderRadius: 6, cursor: "pointer" }}>
                    <Icon name={M.areaTypeIcon[a.type]} size={15} color="#8a8e88" />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f" }}>{a.name}</div>
                      <div style={{ fontSize: 11.5, color: "#a8aca6" }}>{a.type} · {a.sub}</div>
                    </div>
                    <Icon name="plus" size={15} color="#006747" />
                  </div>
                ))}
              </div>
            )}
          </div>
          <div style={{ flex: 1 }} />
          <span style={{ fontSize: 12, color: "#bcbfba" }}>{area ? `${area.type} · ${area.sub}` : ""}</span>
        </div>
      </div>

      {/* FILTER BAR */}
      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 14, flexWrap: "wrap" }}>
        <div style={{ display: "inline-flex", background: "#fff", borderRadius: 8, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.08)", padding: 3 }}>
          {M.timeframes.map((t) => (
            <button key={t.id} onClick={() => setTf(t.id)} style={{ fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, cursor: "pointer", border: 0, borderRadius: 6, padding: "6px 13px",
              background: tf === t.id ? "#006747" : "transparent", color: tf === t.id ? "#fff" : "#6b706a" }}>{t.label}</button>
          ))}
        </div>
        <FilterPill icon="home" value={ptype} options={M.propTypes} onChange={setPtype} />
        <FilterPill icon="bed-double" value={beds} options={M.bedOpts} onChange={setBeds} />
        <button onClick={() => setCompare(!compare)} style={{ display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, cursor: "pointer",
          padding: "8px 12px", borderRadius: 8, border: compare ? "1px solid #006747" : "1px solid #e2e0d8", background: compare ? "#eef4f1" : "#fff", color: compare ? "#006747" : "#6b706a" }}>
          <Icon name={compare ? "check" : "calendar-range"} size={14} color={compare ? "#006747" : "#8a8e88"} /> Compare to last year
        </button>
        {compare && <FilterPill icon="calendar-range" value={M.comparePeriods.find((p) => p.id === cmpPeriod).label} options={M.comparePeriods.map((p) => p.label)} onChange={(lab) => setCmpPeriod(M.comparePeriods.find((p) => p.label === lab).id)} />}
        <div style={{ flex: 1 }} />
        <span style={{ fontSize: 12, color: "#bcbfba", display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="refresh-cw" size={12} color="#bcbfba" /> Updated today · Miami MLS</span>
      </div>

      {/* MAIN: dashboard + right rail */}
      <div className="mi-grid" style={{ display: "grid", gridTemplateColumns: "1fr 340px", gap: 16, alignItems: "start" }}>
        <div style={{ minWidth: 0, display: "flex", flexDirection: "column", gap: 14 }}>
          {/* KPI ROW */}
          <div className="mi-kpis" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 12 }}>
            {kpis.map((k) => {
              const good = k.lowerBetter ? k.delta < 0 : k.delta > 0;
              return (
                <div key={k.label} style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "13px 15px" }}>
                  <div style={{ fontSize: 10.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: "1px", color: "#8a8e88" }}>{k.label}</div>
                  <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 8, marginTop: 7 }}>
                    <div>
                      <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 23, fontWeight: 700, letterSpacing: "-0.8px", color: "#1d241f", lineHeight: 1 }}>{k.raw || k.val}</div>
                      <div style={{ fontSize: 11.5, fontWeight: 600, marginTop: 6, color: good ? "#1f8a5b" : "#c0612f", display: "inline-flex", alignItems: "center", gap: 3 }}>
                        <Icon name={k.delta >= 0 ? "arrow-up-right" : "arrow-down-right"} size={12} color={good ? "#1f8a5b" : "#c0612f"} />
                        {Math.abs(k.delta).toFixed(1)}% <span style={{ color: "#bcbfba", fontWeight: 400 }}>YoY</span>
                      </div>
                    </div>
                    <Sparkline values={k.series} color={good ? "#1f8a5b" : "#c0612f"} w={84} h={34} />
                  </div>
                </div>
              );
            })}
          </div>

          {/* CHARTS GRID */}
          <div className="mi-charts" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
            <ChartCard id="price" full title="Median sale price" sub={`${area ? area.name : ""} · trailing ${tf}`}
              action={<span style={{ fontFamily: "'Space Mono', monospace", fontSize: 13, fontWeight: 700, color: "#006747" }}>{fmtMoney(last(data.price))}</span>}>
              <AreaChart series={data.price} labels={data.labels} color={CC.GREEN} compare={compare ? { values: data.pricePrior } : null} />
              {compare && <Legend items={[{ label: "This year", color: CC.GREEN }, { label: "Same period last year", color: CC.AXIS, dash: true }]} />}
            </ChartCard>

            <ChartCard id="ppsf" title="Median price / sqft" sub={`trailing ${tf}`}>
              <AreaChart series={data.ppsf} labels={data.labels} color={CC.TEAL} yfmt={(v) => "$" + Math.round(v)} h={200} compare={compare ? { values: data.ppsfPrior } : null} />
              {compare && <Legend items={[{ label: "This year", color: CC.TEAL }, { label: "Last year", color: CC.AXIS, dash: true }]} />}
            </ChartCard>

            <ChartCard id="supply" title="New listings vs. sold" sub="monthly volume">
              <BarChart groups={[{ values: data.newListings }, { values: data.sold }]} labels={data.labels} colors={[CC.GREEN, CC.ORANGE]} h={200} />
              <Legend items={[{ label: "New listings", color: CC.GREEN }, { label: "Sold", color: CC.ORANGE }]} />
            </ChartCard>

            <ChartCard id="dom" title="Days on market" sub={`median · trailing ${tf}`}>
              <AreaChart series={data.dom} labels={data.labels} color={CC.ORANGE} yfmt={(v) => Math.round(v) + "d"} h={200} area={false} compare={compare ? { values: data.domPrior } : null} />
              {compare && <Legend items={[{ label: "This year", color: CC.ORANGE }, { label: "Last year", color: CC.AXIS, dash: true }]} />}
            </ChartCard>

            <ChartCard id="dist" title="Price quartiles" sub="closed sales split into four equal groups">
              <Quartiles data={data} />
            </ChartCard>

            <ChartCard id="gauges" full title="Market temperature" sub="how competitive the market is right now">
              <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 12, alignItems: "center" }}>
                <div style={{ textAlign: "center" }}>
                  <Gauge value={b.temp} label={b.temp} sub="Market Action Index" color={b.temp > 60 ? "#c0612f" : b.temp > 45 ? "#e0a020" : "#2a6f8a"} />
                  <div style={{ fontSize: 12, fontWeight: 600, color: b.temp > 60 ? "#c0612f" : "#2a6f8a", marginTop: -6 }}>{b.temp > 60 ? "Seller's market" : b.temp > 45 ? "Balanced" : "Buyer's market"}</div>
                </div>
                <div style={{ textAlign: "center" }}>
                  <Gauge value={b.stl} min={90} max={105} label={b.stl.toFixed(1) + "%"} sub="Sale-to-list ratio" color="#006747" />
                  <div style={{ fontSize: 12, color: "#8a8e88", marginTop: -6 }}>Homes selling near asking</div>
                </div>
                <div style={{ textAlign: "center" }}>
                  <Gauge value={6 - b.moi} min={0} max={6} label={b.moi.toFixed(1)} sub="Months of supply" color="#2a6f8a" />
                  <div style={{ fontSize: 12, color: "#8a8e88", marginTop: -6 }}>{b.moi < 4 ? "Low inventory" : "Healthy inventory"}</div>
                </div>
              </div>
            </ChartCard>
          </div>
        </div>

        {/* RIGHT RAIL */}
        <div className="mi-rail" style={{ position: "sticky", top: 20, display: "flex", flexDirection: "column", gap: 14 }}>
          <AskBox area={area} />
          <DigestSetup area={area} />
        </div>
      </div>
    </div>
  );
}

// ---- price quartiles (always 4 equal-count groups; drill into each) ----
function Quartiles({ data }) {
  const [sel, setSel] = useState(1);
  const qs = data.quartiles;
  const maxC = Math.max(...qs.map((q) => q.count));
  const colors = ["#2a6f8a", "#1f8a5b", "#006747", "#c0612f"];
  const q = qs[sel];
  const stat = (label, val, sub) => (
    <div style={{ background: "#f7f6f1", borderRadius: 6, padding: "9px 10px" }}>
      <div style={{ fontSize: 9.5, color: "#8a8e88", textTransform: "uppercase", letterSpacing: ".6px" }}>{label}</div>
      <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 15, fontWeight: 700, color: "#1d241f", marginTop: 3 }}>{val}</div>
      {sub && <div style={{ fontSize: 10.5, color: "#a8aca6", marginTop: 1 }}>{sub}</div>}
    </div>
  );
  return (
    <div>
      {/* bars */}
      <div style={{ display: "flex", gap: 10, alignItems: "flex-end", height: 132 }}>
        {qs.map((qq, i) => {
          const on = i === sel;
          const h = 34 + (qq.count / maxC) * 70;
          return (
            <button key={qq.q} onClick={() => setSel(i)} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 0, background: "transparent", border: 0, cursor: "pointer", fontFamily: "inherit", height: "100%", justifyContent: "flex-end" }}>
              <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 12, fontWeight: 700, color: on ? colors[i] : "#a8aca6", marginBottom: 4 }}>{qq.count}</span>
              <div style={{ width: "100%", height: h, borderRadius: "3px 3px 0 0", background: on ? colors[i] : "#e4e1d8", transition: "all .15s", boxShadow: on ? "inset 0 0 0 1px rgba(0,0,0,.06)" : "none" }} />
              <div style={{ marginTop: 7, textAlign: "center" }}>
                <div style={{ fontSize: 12, fontWeight: 700, color: on ? "#1d241f" : "#6b706a" }}>{qq.q}</div>
                <div style={{ fontSize: 10.5, color: "#a8aca6", marginTop: 1 }}>{qq.band}</div>
              </div>
            </button>
          );
        })}
      </div>

      {/* drill-in for selected quartile */}
      <div style={{ marginTop: 14, borderTop: "1px solid #f1f0ea", paddingTop: 13 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 10 }}>
          <span style={{ width: 10, height: 10, borderRadius: 2, background: colors[sel] }} />
          <span style={{ fontSize: 13, fontWeight: 600, color: "#1d241f" }}>{q.q} · {q.band}</span>
          <span style={{ fontSize: 12, color: "#a8aca6" }}>· {q.count} sales</span>
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 9 }}>
          {stat("Median", "$" + (q.median / 1000000 >= 1 ? (q.median / 1000000).toFixed(2) + "M" : Math.round(q.median / 1000) + "K"))}
          {stat("$ / sqft", "$" + q.ppsf)}
          {stat("Days on mkt", q.dom + "d", (q.domYoY >= 0 ? "+" : "") + q.domYoY + "d YoY")}
          {stat("Sale-to-list", q.stl + "%")}
        </div>
      </div>
    </div>
  );
}

// ---- filter pill (popover select) ----
function FilterPill({ icon, value, options, onChange }) {
  const [open, setOpen] = useState(false);
  return (
    <div style={{ position: "relative" }}>
      <button onClick={() => setOpen(!open)} style={{ display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, cursor: "pointer", padding: "8px 12px", borderRadius: 8, border: "1px solid #e2e0d8", background: "#fff", color: "#4a504a" }}>
        <Icon name={icon} size={14} color="#8a8e88" /> {value} <Icon name="chevron-down" size={13} color="#a8aca6" />
      </button>
      {open && (
        <div style={{ position: "absolute", top: "calc(100% + 6px)", left: 0, minWidth: 160, background: "#fff", borderRadius: 8, boxShadow: "0 8px 28px rgba(0,0,0,.16), inset 0 0 0 1px rgba(0,0,0,.06)", padding: 6, zIndex: 20 }}>
          {options.map((o) => (
            <div key={o} onClick={() => { onChange(o); setOpen(false); }} className="rc-nav-item" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "8px 10px", borderRadius: 6, cursor: "pointer", fontSize: 13, color: "#1d241f" }}>
              {o} {o === value && <Icon name="check" size={14} color="#006747" />}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ---- AI ask box ----
function AskBox({ area }) {
  const M = window.RC_MARKET;
  const [q, setQ] = useState("");
  const [a, setA] = useState(null);
  const [loading, setLoading] = useState(false);
  const ask = async (question) => {
    const ques = (question || q).trim();
    if (!ques) return;
    setQ(ques); setA(null); setLoading(true);
    const fallback = (M.aiSamples.find((s) => s.q === ques) || M.aiSamples[0]).a;
    try {
      if (window.claude && window.claude.complete) {
        const txt = await window.claude.complete(`You are a real-estate market analyst embedded in an MLS tool. The agent is looking at the ${area ? area.name : "selected"} market in Austin, TX. Answer in 2-3 concise sentences with specific, realistic numbers. Question: ${ques}`);
        setA(txt || fallback);
      } else { await new Promise((r) => setTimeout(r, 700)); setA(fallback); }
    } catch (e) { setA(fallback); }
    setLoading(false);
  };
  return (
    <div style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", overflow: "hidden" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "13px 15px", borderBottom: "1px solid #f1f0ea" }}>
        <span style={{ width: 26, height: 26, borderRadius: "50%", background: "#eef4f1", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="sparkles" size={15} color="#006747" /></span>
        <h3 style={{ margin: 0, fontSize: 14.5, fontWeight: 600, color: "#1d241f", flex: 1 }}>Ask about this market</h3>
      </div>
      <div style={{ padding: 15 }}>
        <div style={{ display: "flex", gap: 8, alignItems: "flex-end", background: "#f7f6f1", borderRadius: 8, padding: "8px 8px 8px 12px", border: "1px solid #ece9e0" }}>
          <textarea value={q} onChange={(e) => setQ(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); ask(); } }}
            placeholder={`Ask about ${area ? area.name : "this area"}…`} rows={2}
            style={{ flex: 1, border: 0, background: "transparent", outline: 0, resize: "none", fontFamily: "inherit", fontSize: 13, color: "#1d241f", lineHeight: 1.4 }} />
          <button onClick={() => ask()} disabled={loading} style={{ width: 32, height: 32, borderRadius: 7, border: 0, background: "#006747", color: "#fff", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center", flex: "none", opacity: loading ? 0.6 : 1 }}>
            <Icon name={loading ? "loader" : "arrow-up"} size={16} color="#fff" style={loading ? { animation: "rc-spin 1s linear infinite" } : {}} />
          </button>
        </div>
        {!a && !loading && (
          <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 11 }}>
            {M.aiSamples.map((s) => (
              <button key={s.q} onClick={() => ask(s.q)} style={{ textAlign: "left", fontFamily: "inherit", fontSize: 12.5, color: "#006747", background: "#f4f6f4", border: "1px solid #e6ece8", borderRadius: 7, padding: "8px 11px", cursor: "pointer", display: "flex", alignItems: "center", gap: 8 }}>
                <Icon name="corner-down-right" size={13} color="#8aa99a" /> {s.q}
              </button>
            ))}
          </div>
        )}
        {loading && <div style={{ marginTop: 12, fontSize: 12.5, color: "#8a8e88", display: "flex", alignItems: "center", gap: 8 }}><Icon name="loader" size={14} color="#8a8e88" style={{ animation: "rc-spin 1s linear infinite" }} /> Analyzing {area ? area.name : "the market"}…</div>}
        {a && !loading && (
          <div style={{ marginTop: 12 }}>
            <div style={{ fontSize: 13, color: "#2d332e", lineHeight: 1.55, background: "#f7f6f1", borderRadius: 8, padding: "12px 13px", borderLeft: "2.5px solid #006747" }}>{a}</div>
            <div style={{ display: "flex", gap: 14, marginTop: 9 }}>
              <button onClick={() => { setA(null); setQ(""); }} style={{ fontFamily: "inherit", fontSize: 12, fontWeight: 600, color: "#006747", background: "none", border: 0, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="rotate-ccw" size={13} color="#006747" /> Ask another</button>
              <button style={{ fontFamily: "inherit", fontSize: 12, fontWeight: 600, color: "#8a8e88", background: "none", border: 0, cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="copy" size={13} color="#8a8e88" /> Add to client update</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ---- client digest setup ----
function DigestSetup({ area }) {
  const M = window.RC_MARKET;
  const [clients, setClients] = useState(M.digestClients);
  const [sel, setSel] = useState(0); // which client the preview shows
  const toggleStatus = (i) => setClients(clients.map((c, j) => j === i ? { ...c, status: c.status === "active" ? "paused" : "active" } : c));
  const setScope = (i, st) => setClients(clients.map((c, j) => j === i ? { ...c, scopeType: st } : c));
  const activeN = clients.filter((c) => c.status === "active").length;
  const c = clients[sel] || clients[0];
  const home = c.scopeType === "home";
  const title = home ? (c.homeScope.replace(/^Around\s/, "").replace(/^.+·\s/, "")) : c.marketScope.replace(" — whole market", "");
  return (
    <div style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", overflow: "hidden" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "13px 15px", borderBottom: "1px solid #f1f0ea" }}>
        <span style={{ width: 26, height: 26, borderRadius: "50%", background: "#faf0e8", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="mail" size={15} color="#c0612f" /></span>
        <h3 style={{ margin: 0, fontSize: 14.5, fontWeight: 600, color: "#1d241f", flex: 1 }}>Client market updates</h3>
        <span style={{ fontSize: 11.5, fontWeight: 600, color: "#1f8a5b", background: "#e8f4ee", borderRadius: 999, padding: "2px 8px" }}>{activeN} active</span>
      </div>

      {/* preview — reflects the selected client's own scope */}
      <div style={{ padding: "13px 15px", borderBottom: "1px solid #f1f0ea" }}>
        <div style={{ fontSize: 11, color: "#a8aca6", marginBottom: 7, display: "flex", alignItems: "center", gap: 6 }}>
          <Icon name="eye" size={12} color="#a8aca6" /> Preview for <strong style={{ color: "#6b706a", fontWeight: 600 }}>{c.name}</strong>
        </div>
        <div style={{ borderRadius: 8, overflow: "hidden", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)" }}>
          <div style={{ background: "#006747", padding: "11px 13px", color: "#fff" }}>
            <div style={{ fontSize: 9.5, fontWeight: 600, letterSpacing: "1.4px", textTransform: "uppercase", opacity: 0.7 }}>{home ? (c.deal === "Selling" ? "Your home's market update" : "Your home search update") : "Your monthly market update"}</div>
            <div style={{ fontSize: 15, fontWeight: 600, marginTop: 3 }}>{title} · June 2026</div>
          </div>
          <div style={{ padding: "12px 13px", background: "#fff" }}>
            <div style={{ fontSize: 12, color: "#4a504a", lineHeight: 1.5 }}>
              {home ? <>Homes near {c.deal === "Selling" ? "your listing" : "this area"} are <strong style={{ color: "#1f8a5b" }}>up 6.4%</strong> over the past year{c.deal === "Selling" ? <>. Your estimated value is <strong>$812K</strong>.</> : <> — buyers have a bit more room than last spring.</>}</>
                    : <>Values are <strong style={{ color: "#1f8a5b" }}>up 6.4%</strong> year-over-year and inventory is <strong>up 24%</strong>, giving buyers more negotiating room.</>}
            </div>
            <div style={{ display: "flex", gap: 8, marginTop: 10 }}>
              <div style={{ flex: 1, background: "#f7f6f1", borderRadius: 6, padding: "8px 9px" }}>
                <div style={{ fontSize: 9, color: "#8a8e88", textTransform: "uppercase", letterSpacing: ".5px" }}>{home && c.deal === "Selling" ? "Est. value" : "Median"}</div>
                <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 14, fontWeight: 700, color: "#1d241f" }}>{home && c.deal === "Selling" ? "$812K" : "$785K"}</div>
              </div>
              <div style={{ flex: 1, background: "#f7f6f1", borderRadius: 6, padding: "8px 9px" }}>
                <div style={{ fontSize: 9, color: "#8a8e88", textTransform: "uppercase", letterSpacing: ".5px" }}>YoY</div>
                <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 14, fontWeight: 700, color: "#1f8a5b" }}>+6.4%</div>
              </div>
              <div style={{ flex: "none", display: "flex", alignItems: "flex-end" }}><Sparkline values={[0.74, 0.75, 0.77, 0.78, 0.8, 0.81]} color="#006747" w={56} h={34} /></div>
            </div>
          </div>
        </div>
        <div style={{ fontSize: 11, color: "#a8aca6", textAlign: "center", marginTop: 7 }}>What this client receives — auto-branded to you</div>
      </div>

      {/* recipients — each chooses their own scope */}
      <div>
        {clients.map((cl, i) => {
          const isHome = cl.scopeType === "home";
          const seld = i === sel;
          return (
            <div key={cl.name} onClick={() => setSel(i)} className="rc-row" style={{ display: "flex", alignItems: "flex-start", gap: 10, padding: "11px 15px", borderTop: i ? "1px solid #f4f3ee" : "none", cursor: "pointer", background: seld ? "#f6f8f6" : "transparent" }}>
              <div style={{ width: 30, height: 30, borderRadius: "50%", background: cl.status === "active" ? "#006747" : "#d8d6cd", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 600, flex: "none", marginTop: 1 }}>{cl.initials}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                  <span style={{ fontSize: 13, fontWeight: 600, color: "#1d241f" }}>{cl.name}</span>
                  {cl.deal && <span style={{ fontSize: 10, fontWeight: 600, color: cl.deal === "Buying" ? "#2a6f8a" : "#c0612f", background: cl.deal === "Buying" ? "#e8f0f3" : "#faece3", borderRadius: 4, padding: "1px 6px" }}>{cl.deal}</span>}
                </div>
                {/* per-client scope choice */}
                <div style={{ display: "inline-flex", background: "#f1f0ea", borderRadius: 7, padding: 2, marginTop: 6 }}>
                  {[["home", "house", "Their home"], ["market", "map", "Whole market"]].map(([st, ic, lab]) => {
                    const on = cl.scopeType === st;
                    return (
                      <button key={st} onClick={(e) => { e.stopPropagation(); setScope(i, st); setSel(i); }} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "inherit", fontSize: 11, fontWeight: 600, cursor: "pointer", border: 0, borderRadius: 5, padding: "4px 8px",
                        background: on ? "#fff" : "transparent", color: on ? "#006747" : "#8a8e88", boxShadow: on ? "0 1px 2px rgba(0,0,0,.12)" : "none" }}>
                        <Icon name={ic} size={11} color={on ? "#006747" : "#a8aca6"} /> {lab}
                      </button>
                    );
                  })}
                </div>
                <div style={{ fontSize: 11.5, color: "#a8aca6", display: "flex", alignItems: "center", gap: 5, marginTop: 6 }}>
                  <Icon name={isHome ? "house" : "map"} size={11} color="#bcbfba" />
                  <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{isHome ? cl.homeScope : cl.marketScope}</span>
                  <span style={{ color: "#d6d4cb" }}>·</span> {cl.freq}
                </div>
              </div>
              <button onClick={(e) => { e.stopPropagation(); toggleStatus(i); }} title={cl.status === "active" ? "Pause" : "Resume"} style={{ position: "relative", width: 34, height: 20, borderRadius: 999, border: 0, cursor: "pointer", background: cl.status === "active" ? "#006747" : "#d2d0c7", flex: "none", transition: "background .15s", marginTop: 2 }}>
                <span style={{ position: "absolute", top: 2, left: cl.status === "active" ? 16 : 2, width: 16, height: 16, borderRadius: "50%", background: "#fff", transition: "left .15s" }} />
              </button>
            </div>
          );
        })}
      </div>
      <div style={{ padding: 12 }}>
        <button style={{ width: "100%", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 7, fontFamily: "inherit", fontSize: 13, fontWeight: 600, cursor: "pointer", padding: "9px", borderRadius: 7, border: "1px dashed #c8c6bc", background: "#fff", color: "#006747" }}>
          <Icon name="user-plus" size={15} color="#006747" /> Add client to updates
        </button>
      </div>
    </div>
  );
}

window.MarketInsights = MarketInsights;
