// Doorpass Control Room — Markets: the national-coverage data view.
// Cumulative verified activity rolled up network-wide, read as ONE flow:
// national stat strip → full-width regional table → the selected region's
// metro table paired with its context cards (your metro, demand mix).
// Respects the global period clock: flows scale by period, stocks and rates don't.
;(function(){
const { CRPage, CRStat, CRCard, CRTh, CRRow, CRChip, CRSpark, CRDef, CRLink, CRIcon, CREmpty, usePeriod, useCRSort, crSorted, crMono } = window;

const fmtK = (n) =>
  n >= 1000000 ? (n / 1000000).toFixed(2) + "M"
  : n >= 10000 ? Math.round(n / 1000) + "K"
  : n >= 1000 ? (n / 1000).toFixed(1) + "K"
  : String(Math.round(n));

// vs-benchmark chip — rate metric, computed against region or national rate.
function VsBench({ pct }) {
  const tone = pct >= 2 ? "good" : pct <= -6 ? "bad" : pct <= -2 ? "warn" : "neutral";
  const label = (pct > 0 ? "+" : "") + pct + "%";
  return <CRChip tone={tone} style={{ fontFamily: "var(--font-mono)", fontWeight: 600 }}>{label}</CRChip>;
}

// Paired horizontal bars — national vs selected region demand mix.
function BandPair({ label, nat, reg, regionName }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "86px 1fr 30px", columnGap: 10, rowGap: 3, alignItems: "center" }}>
      <span style={{ fontSize: 12, fontWeight: 600, color: "var(--neutral-700)", whiteSpace: "nowrap", gridRow: "span 2" }}>{label}</span>
      <span style={{ height: 7, borderRadius: 4, background: "var(--mist-100)", overflow: "hidden", display: "block" }} aria-label={`National ${nat}%`}>
        <span style={{ display: "block", height: "100%", width: `${nat}%`, borderRadius: 4, background: "var(--neutral-300)" }}></span>
      </span>
      <span style={{ ...crMono(11, "var(--neutral-500)"), textAlign: "right" }}>{nat}</span>
      <span style={{ height: 7, borderRadius: 4, background: "var(--mist-100)", overflow: "hidden", display: "block" }} aria-label={`${regionName} ${reg}%`}>
        <span style={{ display: "block", height: "100%", width: `${reg}%`, borderRadius: 4, background: "var(--green-600)" }}></span>
      </span>
      <span style={{ ...crMono(11, "var(--green-800)"), textAlign: "right" }}>{reg}</span>
    </div>
  );
}

function CRMarkets({ go, benchmark = "Region", sparklines = true, priceBands = true, initialRegion }) {
  const D = window.CRData;
  const N = D.network;
  const { period } = usePeriod();
  const key = N.national[period.dataKey] ? period.dataKey : "week";
  const nat = N.national[key];
  const mult = N.periodMult[key];

  const [regionId, setRegionId] = React.useState(initialRegion || "southwest");
  const region = N.regions.find((r) => r.id === regionId) || N.regions[1];
  const metros = N.metrosByRegion[region.id] || [];
  const [sort, toggleSort] = useCRSort("showings");

  const natRate = N.perListing.national;
  const regionRate = region.showings / region.listings;
  const benchRate = benchmark === "National" ? natRate : regionRate;
  const benchLabel = benchmark === "National" ? "vs national rate" : "vs region rate";

  const sortedMetros = crSorted(metros, sort, {
    metro: (m) => m.name,
    showings: (m) => m.showings,
    listings: (m) => m.listings,
    response: (m) => -m.response,
    rate: (m) => m.showings / m.listings,
  });

  const regionCols = sparklines ? "1.3fr 1fr 1fr 0.9fr 0.6fr 120px 0.9fr" : "1.3fr 1fr 1fr 0.9fr 0.6fr 0.9fr";
  const ym = N.yourMetro;
  const sa = N.metrosByRegion[ym.region].find((m) => m.yours);
  const saRate = sa.showings / sa.listings;
  const homeRegion = N.regions.find((r) => r.id === ym.region);
  const saVsRegion = Math.round((saRate / (homeRegion.showings / homeRegion.listings) - 1) * 100);
  const saVsNational = Math.round((saRate / natRate - 1) * 100);

  return (
    <CRPage
      label="markets"
      eyebrow="Doorpass network · national coverage"
      title="Markets"
      sub="Cumulative verified activity across every Doorpass market — aggregated and anonymized, never buyer-identifiable."
      actions={<CRChip tone="info"><CRIcon name="globe-2" size={12} color="currentColor" />L1 aggregate · {period.window}</CRChip>}
    >
      {/* National stat strip — flows accumulate with the period; listings are a stock. */}
      <div style={{ display: "flex", gap: 12, marginBottom: 16 }}>
        <CRStat label="Verified showings" value={nat.showings} delta={nat.sDelta} good={true} info="netshow" />
        <CRStat label="Showing requests" value={nat.requests} delta={nat.rDelta} good={true} info="requests" />
        <CRStat label="Active listings" value={nat.listings} delta={nat.lDelta} good={true} note="stock · active now" info="netlistings" />
        <CRStat label="Median response" value={nat.response} unit="min" delta={nat.respDelta} good={true} info="response" />
        <CRStat label="No-show rate" value={nat.noshow} delta={nat.nDelta} good={true} info="noshowrate" />
      </div>

      {/* Regions — full width so the table breathes; every row drills into the
          metro section below, mirroring how Listings → Listing detail works. */}
      <CRCard title="Regions" info="regionshare" hint={`5 regions · ${period.label.toLowerCase()} · click a row to drill in`} style={{ marginBottom: 16 }}>
        <CRTh
          cols={regionCols}
          labels={sparklines ? ["Region", "Verified showings", "Active listings", "Med. response", "Share", "Trend · 8 wk", "Δ"] : ["Region", "Verified showings", "Active listings", "Med. response", "Share", "Δ"]}
          aligns={sparklines ? ["left", "right", "right", "right", "right", "left", "right"] : ["left", "right", "right", "right", "right", "right"]}
          defs={sparklines ? [null, "netshow", "netlistings", "response", "regionshare", null, null] : [null, "netshow", "netlistings", "response", "regionshare", null]}
        />
        {N.regions.map((r, i) => {
          const on = r.id === regionId;
          return (
            <CRRow key={r.id} cols={regionCols} last={i === N.regions.length - 1} onClick={() => setRegionId(r.id)} ariaLabel={`${r.name} — open metro detail`}>
              <span style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
                <span style={{ fontSize: 13, fontWeight: on ? 800 : 700, color: on ? "var(--green-900)" : "var(--green-950)", whiteSpace: "nowrap" }}>{r.name}</span>
                {r.yours && <CRChip tone="good" style={{ fontSize: 10.5, padding: "1px 7px" }}>You</CRChip>}
              </span>
              <span style={{ ...crMono(13), textAlign: "right" }}>{fmtK(r.showings * mult)}</span>
              <span style={{ ...crMono(12.5, "var(--neutral-700)"), textAlign: "right" }}>{fmtK(r.listings)}</span>
              <span style={{ ...crMono(12.5, "var(--neutral-700)"), textAlign: "right" }}>{r.response} min</span>
              <span style={{ ...crMono(12.5, "var(--neutral-700)"), textAlign: "right" }}>{r.share}%</span>
              {sparklines && <CRSpark data={r.trend} w={112} color={on ? "var(--green-600)" : "var(--neutral-300)"} />}
              <span style={{ display: "flex", justifyContent: "flex-end", alignItems: "center", gap: 6 }}>
                <span style={{ ...crMono(12, r.good ? "var(--green-600)" : "var(--red-600)") }}>{r.delta[key]}</span>
                <span className="cr-row-ch" aria-hidden="true"><CRIcon name="chevron-right" size={13} color="var(--neutral-300)" /></span>
              </span>
            </CRRow>
          );
        })}
      </CRCard>

      {/* Drill section — the selected region's metros, with the context cards that
          describe the same slice sitting beside them instead of floating above. */}
      <div style={{ display: "grid", gridTemplateColumns: "1.55fr 1fr", gap: 16, alignItems: "start" }}>
        <CRCard
          title={`${region.name} — metros`}
          info="perlisting"
          hint={`top ${metros.length} of ${region.metros} metros`}
          action={<CRChip tone="neutral">{benchLabel}</CRChip>}
        >
          <CRTh
            cols="minmax(120px,1fr) 82px 72px 68px 90px 74px"
            labels={["Metro", "Showings", "Listings", "Resp.", "Listing / wk", "vs bench."]}
            aligns={["left", "right", "right", "right", "right", "right"]}
            keys={["metro", "showings", "listings", "response", "rate", null]}
            sort={sort}
            onSort={toggleSort}
          />
          {sortedMetros.length === 0 && <CREmpty title="No metro data yet" body="This region is still onboarding its first markets." />}
          {sortedMetros.map((m, i) => {
            const rate = m.showings / m.listings;
            const pct = Math.round((rate / benchRate - 1) * 100);
            return (
              <CRRow key={m.name} cols="minmax(120px,1fr) 82px 72px 68px 90px 74px" last={i === sortedMetros.length - 1}
                onClick={m.yours ? () => go("overview") : undefined}
                ariaLabel={m.yours ? "San Antonio — open your team overview" : undefined}>
                <span style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
                  <span style={{ fontSize: 13, fontWeight: 700, color: "var(--green-950)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{m.name}</span>
                  {m.yours && <CRChip tone="good" style={{ fontSize: 10.5, padding: "1px 7px" }}>Your metro</CRChip>}
                </span>
                <span style={{ ...crMono(13), textAlign: "right" }}>{fmtK(m.showings * mult)}</span>
                <span style={{ ...crMono(12.5, "var(--neutral-700)"), textAlign: "right" }}>{fmtK(m.listings)}</span>
                <span style={{ ...crMono(12.5, "var(--neutral-700)"), textAlign: "right" }}>{m.response} min</span>
                <span style={{ ...crMono(13), textAlign: "right" }}>{rate.toFixed(1)}</span>
                <span style={{ display: "flex", justifyContent: "flex-end" }}><VsBench pct={pct} /></span>
              </CRRow>
            );
          })}
        </CRCard>

        <div style={{ display: "flex", flexDirection: "column", gap: 16, minWidth: 0 }}>
          {/* Your metro in network context — the bridge back to the team views. */}
          <CRCard title="Your metro in context" info="metrorank" action={<CRLink onClick={() => go("overview")} size={11.5} weight={700} color="var(--green-800)">team overview →</CRLink>}>
            <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginBottom: 4 }}>
              <span style={{ fontSize: 17, fontWeight: 800, color: "var(--green-950)", letterSpacing: "-0.01em" }}>{ym.name}</span>
              <span style={{ fontSize: 12, fontWeight: 600, color: "var(--neutral-500)" }}>Southwest · rank <span style={crMono(12, "var(--green-950)")}>#{ym.rank}</span> of {ym.of} by verified showings</span>
            </div>
            <div style={{ display: "flex", flexDirection: "column" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "9px 0", borderBottom: "1px solid var(--line-200)" }}>
                <span style={{ flex: 1, fontSize: 12.5, fontWeight: 600, color: "var(--neutral-700)", display: "inline-flex", alignItems: "center", gap: 5 }}>Showings per listing / wk<CRDef k="perlisting" align="left" /></span>
                <span style={crMono(13)}>{saRate.toFixed(1)}</span>
                <VsBench pct={benchmark === "National" ? saVsNational : saVsRegion} />
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "9px 0", borderBottom: "1px solid var(--line-200)" }}>
                <span style={{ flex: 1, fontSize: 12.5, fontWeight: 600, color: "var(--neutral-700)", display: "inline-flex", alignItems: "center", gap: 5 }}>Brooks share of comp set<CRDef k="share" align="left" /></span>
                <span style={crMono(13)}>{ym.share}</span>
                <CRLink onClick={() => go("pipeline")} size={11.5} weight={700} color="var(--green-800)">evidence →</CRLink>
              </div>
              <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "9px 0 2px" }}>
                <span style={{ flex: 1, fontSize: 12.5, fontWeight: 600, color: "var(--neutral-700)" }}>Benchmark</span>
                <span style={{ fontSize: 11.5, fontWeight: 600, color: "var(--neutral-500)" }}>{benchLabel} · {benchRate.toFixed(1)}/wk</span>
              </div>
            </div>
          </CRCard>

          {/* Demand mix — where verified buyers actually tour, national vs region. */}
          {priceBands && (
            <CRCard title="Demand by price band" hint="% of verified showings">
              <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 12 }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11.5, fontWeight: 600, color: "var(--neutral-500)" }}>
                  <span style={{ width: 8, height: 8, borderRadius: 4, background: "var(--neutral-300)", display: "inline-block" }}></span>National
                </span>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 11.5, fontWeight: 600, color: "var(--green-800)" }}>
                  <span style={{ width: 8, height: 8, borderRadius: 4, background: "var(--green-600)", display: "inline-block" }}></span>{region.name}
                </span>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
                {N.bands.map((b, i) => (
                  <BandPair key={b} label={b} nat={N.nationalBands[i]} reg={N.regionBands[region.id][i]} regionName={region.name} />
                ))}
              </div>
            </CRCard>
          )}
        </div>
      </div>
    </CRPage>
  );
}

Object.assign(window, { CRMarkets });
})();
