// Control Room: Pipeline — market demand + recruiting intelligence.
// v2: period-aware stats that drill, sr-only chart summaries, consideration-set
// rows marked "Yours" open their listing, recruiting table sorts + searches and
// carries the no-show flags promised by the Operations report.
;(function(){
const DS = window.DoorpassDesignSystem_eaad52;
const { Button, SegmentedControl } = DS;
const D = window.CRData;
const { CRIcon, CRPage, CRStat, CRChip, CRSpark, CRBar, CRCard, CRTh, CRRow, CRLink,
        CRPhoto, CRSearch, CREmpty, usePeriod, useCRSort, crSorted, crMono } = window;

function PipelineTabs({ view, go }) {
  return (
    <SegmentedControl
      options={[{ label: "Market demand", value: "pipeline" }, { label: "Recruiting", value: "recruiting" }]}
      value={view}
      onChange={(v) => go(v)}
      style={{ width: 248 }}
    />
  );
}

/* ============ 05 · Pipeline — buyer-side demand ============ */

function CRPipeline({ go }) {
  const { period } = usePeriod();
  const stats = D.pipelineStats[period.dataKey];
  const maxBand = Math.max(...D.priceBands.map((b) => b.n));
  const maxHood = Math.max(...D.hoods.map((h) => h.n));
  const drill = {
    buyers: () => go("recruiting"),
    tours: () => go("activity", { filter: "entry" }),
    duration: () => go("activity", { filter: "entry" }),
  };
  return (
    <CRPage
      label="05 Pipeline · demand"
      eyebrow="Aggregate verified flows · anonymized by default"
      title="Pipeline"
      sub="The team's market radar — verified buyer-agent activity around your listings."
      actions={<PipelineTabs view="pipeline" go={go} />}
    >
      <div style={{ display: "flex", gap: 12, marginBottom: 16 }}>
        {stats.map((s) => (
          <CRStat key={s.k} label={s.label} value={s.v} unit={s.unit} delta={s.delta} good={s.good} note={s.note} info={s.k === "buyers" ? "overlap" : s.k === "tours" ? "showings" : "duration"} onClick={drill[s.k]} />
        ))}
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16, marginBottom: 16 }}>
        <CRCard title="Buyer-agents touring, by price band" hint={period.label.toLowerCase()}>
          <span className="sr-only">Demand peaks at 17 buyer-agents in the $350–500K band; lightest at $1M+ with 4.</span>
          <div aria-hidden="true" style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {D.priceBands.map((b) => <CRBar key={b.band} label={b.band} n={b.n} max={maxBand} />)}
          </div>
          <div style={{ marginTop: 12, fontSize: 12, fontWeight: 500, color: "var(--neutral-700)" }}>
            Demand is deepest at $350–500K — where you hold only <CRLink onClick={() => go("listings")} size={12} weight={700} color="var(--green-800)">4 of 14 listings</CRLink>.
          </div>
        </CRCard>
        <CRCard title="Demand by neighborhood" hint="verified tours">
          <span className="sr-only">Stone Oak leads with 21 verified tours; Medical Center has the fewest at 6.</span>
          <div aria-hidden="true" style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {D.hoods.map((h) => <CRBar key={h.hood} label={h.hood} n={h.n} max={maxHood} color="var(--green-800)" />)}
          </div>
          <div style={{ marginTop: 12, fontSize: 12, fontWeight: 500, color: "var(--neutral-700)" }}>
            Stone Oak absorbs the most verified buyer attention in your footprint.
          </div>
        </CRCard>
      </div>

      <CRCard title="Consideration set — buyers touring 412 Oakmont Dr also toured" info="overlap" hint="tours as behavioral comps" pad={10}
        action={<CRLink onClick={() => go("listing", "oakmont")} size={11.5} weight={700} color="var(--green-800)">412 Oakmont →</CRLink>}>
        <CRTh cols="1.3fr 130px 80px 1fr 90px" labels={["Listing", "Neighborhood", "Price", "Overlap", ""]} aligns={["left", "left", "right", "left", "left"]} />
        {D.considerationSet.map((c, i) => {
          const ours = c.ours ? D.listing(c.ours) : null;
          return (
            <CRRow key={c.addr} cols="1.3fr 130px 80px 1fr 90px" last={i === D.considerationSet.length - 1}
              onClick={ours ? () => go("listing", ours.id) : undefined}
              ariaLabel={ours ? `${c.addr} — open your listing` : undefined}>
              <span style={{ display: "flex", alignItems: "center", gap: 10, minWidth: 0 }}>
                <CRPhoto listing={ours} w={30} h={24} radius={6} />
                <span style={{ fontSize: 13, fontWeight: 700, color: "var(--green-950)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.addr}</span>
              </span>
              <span style={{ fontSize: 12, fontWeight: 500, color: "var(--neutral-500)" }}>{c.hood}</span>
              <span style={{ ...crMono(12.5), textAlign: "right" }}>{c.price}</span>
              <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span aria-hidden="true" style={{ display: "inline-flex", gap: 3 }}>
                  {[...Array(5)].map((_, k) => (
                    <span key={k} style={{ width: 14, height: 7, borderRadius: 3, background: k < c.overlap ? "var(--green-600)" : "var(--mist-100)" }}></span>
                  ))}
                </span>
                <span style={{ ...crMono(11.5, "var(--neutral-700)", 500), whiteSpace: "nowrap" }}>{c.overlap} of 5 buyers</span>
              </span>
              <span style={{ display: "flex", alignItems: "center", gap: 6 }}>
                {ours && <CRChip tone="good">Yours</CRChip>}
                {ours && <span className="cr-row-ch"><CRIcon name="chevron-right" size={13} color="var(--neutral-300)" /></span>}
              </span>
            </CRRow>
          );
        })}
      </CRCard>
      <div style={{ marginTop: 10, fontSize: 11.5, fontWeight: 500, color: "var(--neutral-500)", display: "flex", alignItems: "center", gap: 6 }}>
        <CRIcon name="eye-off" size={13} color="var(--neutral-500)" />
        Buyer identities are never shown here — this view is built from aggregate, anonymized flows.
      </div>
    </CRPage>
  );
}

/* ============ 06 · Pipeline — recruiting intelligence ============ */

const RCOLS = "minmax(146px,1.15fr) 118px 60px 78px 94px 82px 100px 92px 104px";
const RSORT = {
  name: (b) => b.name, brokerage: (b) => b.brokerage, tours: (b) => b.tours,
  showings: (b) => b.showings, conv: (b) => b.conv, ontime: (b) => b.ontime, noshow30: (b) => b.noshow30,
};

function CRRecruiting({ go }) {
  // Watch state is shared with the Overview recruiting trigger (A10) — one store.
  const watch = window.useCRWatch();
  const [q, setQ] = React.useState("");
  const [sort, onSort] = useCRSort("tours", "desc");
  const ql = q.trim().toLowerCase();
  const rows = crSorted(
    D.buyerAgents.filter((b) => !ql || (b.name + " " + b.brokerage).toLowerCase().includes(ql)),
    sort, RSORT,
  );
  return (
    <CRPage
      label="06 Pipeline · recruiting"
      eyebrow="Co-broke buyer's agents · verified activity"
      title="Pipeline"
      sub="Buyer's agents ranked by verified performance on your listings."
      actions={<PipelineTabs view="recruiting" go={go} />}
    >
      <div style={{
        marginBottom: 14, display: "flex", gap: 10, alignItems: "center",
        background: "var(--surface-white)", borderRadius: "var(--radius-md)",
        boxShadow: "inset 0 0 0 1px var(--line-200)", padding: "10px 14px",
      }}>
        <CRIcon name="scale" size={15} color="var(--neutral-500)" />
        <span style={{ flex: 1, fontSize: 12, fontWeight: 600, color: "var(--neutral-700)" }}>
          Based on showings of your listings only. Agents appear by name because they transacted with Brooks Group properties — nothing here is purchased lead data.
        </span>
        <CRSearch value={q} onChange={setQ} placeholder="Filter agents…" width={180} />
      </div>

      <CRCard pad={10}>
        <CRTh cols={RCOLS}
          labels={["Agent", "Brokerage", "Tours", "Showings", "Conversion", "On-time", "No-shows · 30d", "Activity · 8 wk", ""]}
          aligns={["left", "left", "right", "right", "right", "right", "right", "left", "left"]}
          keys={["name", "brokerage", "tours", "showings", "conv", "ontime", "noshow30", null, null]}
          defs={[null, null, null, "showings", "conversion", "ontime", "noshow", null, null]}
          sort={sort} onSort={onSort} />
        {rows.length === 0 && (
          <CREmpty title={`No agents match “${q}”`} body="Try a last name or brokerage."
            action={<Button variant="secondary" size="sm" onClick={() => setQ("")}>Clear search</Button>} />
        )}
        {rows.map((b, i) => (
          <CRRow key={b.name} cols={RCOLS} last={i === rows.length - 1}>
            <span style={{ display: "flex", alignItems: "center", gap: 9 }}>
              <span style={{ ...crMono(11, "var(--neutral-300)", 500), width: 16 }}>{String(i + 1).padStart(2, "0")}</span>
              <span style={{ fontSize: 13, fontWeight: 700, color: "var(--green-950)" }}>{b.name}</span>
            </span>
            <span style={{ fontSize: 12, fontWeight: 500, color: "var(--neutral-500)" }}>{b.brokerage}</span>
            <span style={{ ...crMono(12.5), textAlign: "right" }}>{b.tours}</span>
            <span style={{ ...crMono(12.5), textAlign: "right" }}>{b.showings}</span>
            <span style={{ ...crMono(12.5), textAlign: "right" }}>{b.conv ? b.conv + "%" : "—"}</span>
            <span style={{ ...crMono(12.5, b.ontime >= 90 ? "var(--green-800)" : "var(--amber-700)"), textAlign: "right" }}>{b.ontime}%</span>
            <span style={{ textAlign: "right" }}>{b.noshow30 >= 2
              ? <CRChip tone="warn" style={{ fontFamily: "var(--font-mono)", fontWeight: 600 }}>{b.noshow30}</CRChip>
              : <span style={{ ...crMono(12.5, b.noshow30 ? "var(--neutral-700)" : "var(--neutral-300)", 500) }}>{b.noshow30 || "—"}</span>}</span>
            <span><CRSpark data={b.trend} w={80} h={20} /></span>
            <span>
              <Button
                variant={watch[b.name] ? "secondary" : "ghost"} size="sm"
                leadingIcon={<CRIcon name={watch[b.name] ? "check" : "plus"} size={13} />}
                onClick={() => window.CRIntelWatch.toggle(b.name)}
              >{watch[b.name] ? "Watching" : "Watchlist"}</Button>
            </span>
          </CRRow>
        ))}
      </CRCard>

      <div style={{ marginTop: 10, fontSize: 11.5, fontWeight: 500, color: "var(--neutral-500)", display: "flex", alignItems: "center", gap: 6 }}>
        <CRIcon name="info" size={13} color="var(--neutral-500)" />
        On-time = verified arrival within 10 minutes of the pass window. No-show counts reconcile with the
        <CRLink onClick={() => go("operations")} size={11.5} weight={700} color="var(--green-800)"> Operations report</CRLink>.
      </div>
    </CRPage>
  );
}

Object.assign(window, { CRPipeline, CRRecruiting });
})();
