"use client";
import {
  Card,
  DEFAULT_VENUE_COLOR,
  Icon,
  Skeleton,
  VenueLogo,
  __spreadProps,
  __spreadValues,
  cn,
  fallbackLineColors,
  formatMarketProbabilityPercent,
  formatUsd,
  getVenueSummary,
  normalizeProbability,
  normalizeVenueMarketCluster,
  resolveOutcomeTitle,
  resolveResolvedOutcomeLabel,
  resolveVenueLineColor,
  selectPrimaryVenueMarket,
  skeletonViews,
  sortOutcomes
} from "./chunk-WZ55ERDO.mjs";

// src/trading/trading-context/index.tsx
import { useEventTradingContext } from "@agg-build/hooks";

// src/events/orderbook/orderbook.utils.ts
import { hasShape, safeParse } from "@agg-build/sdk";
var isOrderBookLevel = (v) => hasShape(v, {
  price: (p) => typeof p === "number" && p >= 0 && p <= 1,
  size: (s) => typeof s === "number" && s >= 0
});
var isOrderBookRow = (v) => hasShape(v, {
  id: (x) => typeof x === "string",
  venue: (x) => typeof x === "string" && x.length > 0,
  price: (p) => typeof p === "number" && p >= 0 && p <= 1,
  size: (s) => typeof s === "number" && s >= 0,
  total: (t) => typeof t === "number" && t >= 0,
  tone: (x) => x === "positive" || x === "negative"
});
var formatProbabilityCents = (value) => {
  if (value == null) return "-";
  const cents = (value * 100).toFixed(1).replace(/\.0$/, "");
  return `${cents}\xA2`;
};
var resolveOrderBookRows = ({
  data,
  side
}) => {
  if (!(data == null ? void 0 : data.length)) return [];
  const tone = side === "asks" ? "negative" : "positive";
  const rows = data.flatMap((result) => {
    var _a;
    return ((_a = result.orderbook[side]) != null ? _a : []).flatMap(
      (level, index) => {
        const parsedLevel = safeParse(level, isOrderBookLevel);
        if (!parsedLevel.success) return [];
        const parsedRow = safeParse(
          {
            id: `${result.market.id}-${side}-${index}-${parsedLevel.data.price}`,
            venue: result.market.venue,
            price: parsedLevel.data.price,
            size: parsedLevel.data.size,
            total: parsedLevel.data.price * parsedLevel.data.size,
            tone
          },
          isOrderBookRow
        );
        if (!parsedRow.success) return [];
        return [parsedRow.data];
      }
    );
  });
  const sortedRows = [...rows].sort((left, right) => {
    if (side === "asks") return left.price - right.price;
    return right.price - left.price;
  });
  const maxTotal = sortedRows.reduce((currentMax, row) => Math.max(currentMax, row.total), 0) || 1;
  return sortedRows.map((row) => __spreadProps(__spreadValues({}, row), {
    barScale: row.total / maxTotal
  }));
};
var resolveUnifiedOrderBookEntries = ({
  askRows,
  bidRows,
  midPrice,
  spread
}) => {
  const asksDescending = [...askRows].reverse();
  const askCumulativeDepths = new Array(asksDescending.length);
  let cumulative = 0;
  for (let i = asksDescending.length - 1; i >= 0; i--) {
    cumulative += asksDescending[i].total;
    askCumulativeDepths[i] = cumulative;
  }
  const bidCumulativeDepths = new Array(bidRows.length);
  cumulative = 0;
  for (let i = 0; i < bidRows.length; i++) {
    cumulative += bidRows[i].total;
    bidCumulativeDepths[i] = cumulative;
  }
  const maxAskCumulative = askCumulativeDepths.length > 0 ? askCumulativeDepths[0] : 0;
  const maxBidCumulative = bidCumulativeDepths.length > 0 ? bidCumulativeDepths[bidCumulativeDepths.length - 1] : 0;
  const askMax = maxAskCumulative || 1;
  const bidMax = maxBidCumulative || 1;
  const askEntries = asksDescending.map((row, index) => ({
    kind: "ask",
    row,
    cumulativeDepth: askCumulativeDepths[index],
    unifiedBarScale: askCumulativeDepths[index] / askMax
  }));
  const bidEntries = bidRows.map((row, index) => ({
    kind: "bid",
    row,
    cumulativeDepth: bidCumulativeDepths[index],
    unifiedBarScale: bidCumulativeDepths[index] / bidMax
  }));
  const spreadEntry = { kind: "spread", midPrice, spread };
  return [...askEntries, spreadEntry, ...bidEntries];
};

// src/trading/utils.ts
import { resolveAggUiLabels } from "@agg-build/hooks";
import dayjs from "dayjs";
var defaultLabels = resolveAggUiLabels("en-US");
var defaultSettlementSectionLabel = defaultLabels.trading.settlementSection;
var defaultTradingDisclaimer = defaultLabels.trading.disclaimer;
var getTradingDateLabel = (value) => {
  const parsedValue = dayjs(value);
  if (!parsedValue.isValid()) {
    return typeof value === "string" ? value : "";
  }
  return parsedValue.format("MMM D, YYYY");
};
var getTradingVenueLabel = (venue, label) => {
  var _a;
  if (label) return label;
  if (!venue) return "Unknown";
  return (_a = defaultLabels.venues[venue]) != null ? _a : venue;
};
var getTradingValueLabel = ({
  amount,
  minimumFractionDigits = 0,
  maximumFractionDigits = 2
}) => {
  return amount.toLocaleString("en-US", {
    style: "currency",
    currency: "USD",
    minimumFractionDigits,
    maximumFractionDigits
  });
};
var getTradingPriceLabel = (value) => {
  return `${Math.round(value * 100)}\xA2`;
};
var getTradingAveragePriceLabel = (value) => {
  return defaultLabels.trading.averagePrice(value);
};
var getTradingBalanceLabel = (value) => {
  return defaultLabels.trading.balance(formatUsd(value));
};
var getTradingSharesLabel = (value) => {
  return defaultLabels.trading.shares(value);
};
var getTradingSlippageLabel = (value) => {
  return defaultLabels.trading.slippage(value);
};

// src/trading/settlement/index.tsx
import {
  useLabels
} from "@agg-build/hooks";
import { useEffect, useMemo, useState } from "react";

// src/trading/settlement/settlement-text-renderer.tsx
import { Fragment } from "react";

// src/trading/settlement/settlement-text.utils.ts
var stripHtmlFragments = (text) => {
  return text.replace(/<\s*p\s*>/gi, "").replace(/<\s*\/\s*p\s*>/gi, "\n\n").replace(/<\s*br\s*\/?\s*>/gi, "\n").replace(/\r\n/g, "\n");
};
var isListLine = (line) => /^\s*[-*]\s+/.test(line);
var stripBullet = (line) => line.replace(/^\s*[-*]\s+/, "").trim();
var parseSettlementBlocks = (input) => {
  const normalized = stripHtmlFragments(input).trim();
  if (!normalized) return [];
  const paragraphs = normalized.split(/\n{2,}/);
  const blocks = [];
  for (const rawParagraph of paragraphs) {
    const lines = rawParagraph.split("\n").map((line) => line.replace(/\s+$/, "")).filter((line) => line.trim().length > 0);
    if (lines.length === 0) continue;
    if (lines.every(isListLine)) {
      blocks.push({ kind: "list", items: lines.map(stripBullet) });
      continue;
    }
    blocks.push({ kind: "paragraph", lines: lines.map((line) => line.trim()) });
  }
  return blocks;
};
var getFirstSettlementParagraph = (input) => {
  if (!input) return "";
  const blocks = parseSettlementBlocks(input);
  const firstParagraph = blocks.find((block) => block.kind === "paragraph");
  if (!firstParagraph || firstParagraph.kind !== "paragraph") return "";
  return firstParagraph.lines.join(" ").trim();
};
var normalizeSettlementForCompare = (input) => {
  return stripHtmlFragments(input).replace(/\s+/g, " ").trim().toLowerCase();
};
var dedupeSettlementSources = (sources) => {
  const order = ["eventDescription", "marketDescription", "primaryRules"];
  const result = [];
  for (const key of order) {
    const value = sources[key];
    if (typeof value !== "string") continue;
    const trimmed = value.trim();
    if (!trimmed) continue;
    const fingerprint = normalizeSettlementForCompare(trimmed);
    if (!fingerprint) continue;
    if (result.some((block) => block.fingerprint.includes(fingerprint))) continue;
    for (let i = result.length - 1; i >= 0; i -= 1) {
      if (fingerprint.includes(result[i].fingerprint)) result.splice(i, 1);
    }
    result.push({ key, content: trimmed, fingerprint });
  }
  return result.map(({ key, content }) => ({ key, content }));
};

// src/trading/settlement/settlement-text-renderer.tsx
import { jsx, jsxs } from "react/jsx-runtime";
var inlineTokenRegex = new RegExp(
  [
    /\[([^\]\n]+)\]\(([^)\s]+)\)/.source,
    // 1=link text, 2=link href
    /\*\*([^*\n]+?)\*\*/.source,
    // 3=bold inner
    /`([^`\n]+?)`/.source,
    // 4=code inner
    /(https?:\/\/[^\s<>"'`]+)/.source
    // 5=bare url
  ].join("|"),
  "g"
);
var trailingUrlPunctuationRegex = /[.,;:!?)\]]+$/;
var isLinkMatch = (match) => match[1] !== void 0 && match[2] !== void 0;
var linkClassName = "agg-settlement-text-link text-agg-primary underline hover:opacity-80";
var renderInlineSegment = (text, baseKey) => {
  const nodes = [];
  let lastIndex = 0;
  let segmentIndex = 0;
  inlineTokenRegex.lastIndex = 0;
  let match;
  while ((match = inlineTokenRegex.exec(text)) !== null) {
    let matchEnd = match.index + match[0].length;
    let bareUrl = match[5];
    if (bareUrl !== void 0) {
      const trailing = trailingUrlPunctuationRegex.exec(bareUrl);
      if (trailing) {
        const trimmed = bareUrl.slice(0, bareUrl.length - trailing[0].length);
        if (trimmed.length > "https://".length) {
          bareUrl = trimmed;
          matchEnd -= trailing[0].length;
          inlineTokenRegex.lastIndex = matchEnd;
        }
      }
    }
    if (match.index > lastIndex) {
      nodes.push(
        /* @__PURE__ */ jsx(Fragment, { children: text.slice(lastIndex, match.index) }, `${baseKey}-text-${segmentIndex++}`)
      );
    }
    if (isLinkMatch(match)) {
      nodes.push(
        /* @__PURE__ */ jsx(
          "a",
          {
            href: match[2],
            target: "_blank",
            rel: "noopener noreferrer",
            className: linkClassName,
            children: match[1]
          },
          `${baseKey}-link-${segmentIndex++}`
        )
      );
    } else if (match[3] !== void 0) {
      nodes.push(
        /* @__PURE__ */ jsx(
          "strong",
          {
            className: "agg-settlement-text-bold font-agg-bold",
            children: match[3]
          },
          `${baseKey}-bold-${segmentIndex++}`
        )
      );
    } else if (match[4] !== void 0) {
      nodes.push(
        /* @__PURE__ */ jsx(
          "code",
          {
            className: "agg-settlement-text-code rounded-agg-sm bg-agg-secondary-hover px-1 py-0.5 font-mono text-[0.875em]",
            children: match[4]
          },
          `${baseKey}-code-${segmentIndex++}`
        )
      );
    } else if (bareUrl !== void 0) {
      nodes.push(
        /* @__PURE__ */ jsx(
          "a",
          {
            href: bareUrl,
            target: "_blank",
            rel: "noopener noreferrer",
            className: linkClassName,
            children: bareUrl
          },
          `${baseKey}-url-${segmentIndex++}`
        )
      );
    }
    lastIndex = matchEnd;
  }
  if (lastIndex < text.length) {
    nodes.push(
      /* @__PURE__ */ jsx(Fragment, { children: text.slice(lastIndex) }, `${baseKey}-text-${segmentIndex++}`)
    );
  }
  return nodes;
};
var renderBlock = (block, blockIndex) => {
  if (block.kind === "list") {
    return /* @__PURE__ */ jsx(
      "ul",
      {
        className: "agg-settlement-text-list list-disc pl-5 text-agg-sm leading-agg-5 text-agg-foreground",
        children: block.items.map((item, itemIndex) => /* @__PURE__ */ jsx(
          "li",
          {
            className: "agg-settlement-text-list-item",
            children: renderInlineSegment(item, `block-${blockIndex}-item-${itemIndex}`)
          },
          `block-${blockIndex}-item-${itemIndex}`
        ))
      },
      `block-${blockIndex}`
    );
  }
  return /* @__PURE__ */ jsx(
    "p",
    {
      className: "agg-settlement-text-paragraph text-agg-sm leading-agg-5 text-agg-foreground break-words [overflow-wrap:anywhere]",
      children: block.lines.map((line, lineIndex) => /* @__PURE__ */ jsxs(Fragment, { children: [
        lineIndex > 0 ? /* @__PURE__ */ jsx("br", {}) : null,
        renderInlineSegment(line, `block-${blockIndex}-line-${lineIndex}`)
      ] }, `block-${blockIndex}-line-${lineIndex}`))
    },
    `block-${blockIndex}`
  );
};
var SettlementTextRenderer = ({
  content,
  className
}) => {
  const blocks = parseSettlementBlocks(content);
  if (blocks.length === 0) return null;
  return /* @__PURE__ */ jsx("div", { className: cn("agg-settlement-text flex flex-col gap-2", className), children: blocks.map((block, blockIndex) => renderBlock(block, blockIndex)) });
};
SettlementTextRenderer.displayName = "SettlementTextRenderer";

// src/trading/settlement/index.tsx
import { Fragment as Fragment2, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var SETTLEMENT_SECTION_ID = "agg-settlement-section";
var getSettlementDifferenceId = (sectionId, canonicalKey) => {
  return `${sectionId}-difference-${canonicalKey}`;
};
var dateOnlyRegex = /^(\d{4})-(\d{2})-(\d{2})$/;
var isoTimestampWithTimezoneRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:?\d{2})$/i;
var normalizeDifferenceText = (value) => {
  return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
};
var resolveCanonicalDifferenceKey = (difference) => {
  const normalizedType = normalizeDifferenceText(difference.type);
  const combined = normalizeDifferenceText(`${difference.type} ${difference.title}`);
  if (combined.includes("start_date") || combined.includes("open_date")) return "start_date";
  if (combined.includes("end_date") || combined.includes("close_date") || combined.includes("closing_date") || combined.includes("expiration_date") || combined.includes("expiry_date")) {
    return "end_date";
  }
  if (combined.includes("resolution_timing") || combined.includes("resolution_date") || combined.includes("resolution_deadline") || combined.includes("settlement_date") || combined.includes("settlement_deadline") || combined.includes("settlement_timing")) {
    return "resolution_timing";
  }
  return normalizedType || "other";
};
var parseSettlementDateMs = (value) => {
  const trimmed = value.trim();
  const dateOnlyMatch = dateOnlyRegex.exec(trimmed);
  if (dateOnlyMatch) {
    const [, year, month, day] = dateOnlyMatch;
    return Date.UTC(Number(year), Number(month) - 1, Number(day));
  }
  if (!isoTimestampWithTimezoneRegex.test(trimmed)) return null;
  const ms = Date.parse(trimmed);
  return Number.isNaN(ms) ? null : ms;
};
var isDateLikeDifference = (canonicalKey) => {
  return canonicalKey === "resolution_timing" || canonicalKey === "start_date" || canonicalKey === "end_date";
};
var hasEqualNormalizedDateValues = (difference, canonicalKey) => {
  if (!isDateLikeDifference(canonicalKey)) return false;
  const values = Object.values(difference.perVenue);
  if (values.length < 2) return false;
  const timestamps = values.map(parseSettlementDateMs);
  if (timestamps.some((timestamp) => timestamp === null)) return false;
  return new Set(timestamps).size === 1;
};
var resolveDifferenceSeverity = (difference, canonicalKey) => {
  var _a;
  const combined = normalizeDifferenceText(
    `${difference.type} ${difference.title} ${(_a = difference.summary) != null ? _a : ""}`
  );
  if (isDateLikeDifference(canonicalKey)) return "critical";
  if (canonicalKey === "scope" || canonicalKey === "threshold" || canonicalKey === "edge_cases") {
    return "critical";
  }
  if (combined.includes("conflict") || combined.includes("void") || combined.includes("cancel") || combined.includes("postpone") || combined.includes("recount") || combined.includes("overtime") || combined.includes("extra_time")) {
    return "critical";
  }
  return "informational";
};
var mergePerVenueValues = (current, next) => {
  return Object.entries(next).reduce(
    (merged, [venue, value]) => {
      if (merged[venue] === void 0) merged[venue] = value;
      return merged;
    },
    __spreadValues({}, current)
  );
};
var prepareSettlementDifferences = (differences) => {
  const byCanonicalKey = /* @__PURE__ */ new Map();
  for (const [originalIndex, difference] of (differences != null ? differences : []).entries()) {
    const canonicalKey = resolveCanonicalDifferenceKey(difference);
    if (hasEqualNormalizedDateValues(difference, canonicalKey)) continue;
    const existing = byCanonicalKey.get(canonicalKey);
    if (existing) {
      byCanonicalKey.set(canonicalKey, __spreadProps(__spreadValues({}, existing), {
        perVenue: mergePerVenueValues(existing.perVenue, difference.perVenue)
      }));
      continue;
    }
    byCanonicalKey.set(canonicalKey, __spreadProps(__spreadValues({}, difference), {
      canonicalKey,
      severity: resolveDifferenceSeverity(difference, canonicalKey),
      originalIndex
    }));
  }
  return Array.from(byCanonicalKey.values()).sort((left, right) => {
    const severityDelta = Number(right.severity === "critical") - Number(left.severity === "critical");
    if (severityDelta !== 0) return severityDelta;
    return left.originalIndex - right.originalIndex;
  });
};
var formatVenueFallbackLabel = (venue) => {
  return venue.split(/[-_\s]+/).filter(Boolean).map((part) => `${part.slice(0, 1).toUpperCase()}${part.slice(1)}`).join(" ");
};
var resolveSettlementVenueLabel = (venue, labels) => {
  var _a;
  return (_a = labels.venues[venue]) != null ? _a : formatVenueFallbackLabel(venue);
};
var resolveDifferenceVenueKeys = (difference, settlementVenues) => {
  const explicitVenues = Object.keys(difference.perVenue);
  if (!isDateLikeDifference(difference.canonicalKey)) return explicitVenues;
  const allVenues = [...settlementVenues != null ? settlementVenues : [], ...explicitVenues];
  return Array.from(new Set(allVenues.filter((venue) => venue.trim().length > 0)));
};
var resolveDifferenceIconClassName = (canonicalKey) => {
  if (canonicalKey.includes("source") || canonicalKey.includes("url")) return "fi-rr-world";
  if (canonicalKey === "resolution_timing" || canonicalKey.includes("timing")) {
    return "fi-rr-clock";
  }
  if (canonicalKey === "start_date" || canonicalKey.includes("start"))
    return "fi-rr-calendar-clock";
  if (canonicalKey === "end_date" || canonicalKey.includes("end")) return "fi-rr-calendar-clock";
  if (canonicalKey.includes("cancel") || canonicalKey.includes("void") || canonicalKey.includes("postpone")) {
    return "fi-rr-ban";
  }
  if (canonicalKey === "edge_cases" || canonicalKey.includes("edge")) {
    return "fi-rr-triangle-warning";
  }
  if (canonicalKey === "scope") return "fi-rr-layers";
  if (canonicalKey === "threshold") return "fi-rr-tachometer-alt-fastest";
  if (canonicalKey.includes("wording")) return "fi-rr-document";
  return "fi-rr-info";
};
var buildSettlementVenueRules = ({
  eventBlock,
  marketBlock,
  primaryRulesBlock,
  settlementVenueRules
}) => {
  if (settlementVenueRules) return settlementVenueRules;
  const content = [marketBlock == null ? void 0 : marketBlock.content, primaryRulesBlock == null ? void 0 : primaryRulesBlock.content, eventBlock == null ? void 0 : eventBlock.content].filter((value) => typeof value === "string" && value.trim().length > 0).join("\n\n");
  return content ? [{ venue: "polymarket", content }] : [];
};
var getSettlementHeaderClassName = () => {
  return "flex items-center justify-between gap-4";
};
var Settlement = ({
  className,
  id = SETTLEMENT_SECTION_ID,
  sectionLabel = defaultSettlementSectionLabel,
  question,
  eventDescription,
  marketDescription,
  primaryRules,
  settlementDiff,
  settlementVenues,
  settlementVenueRules,
  isLoading = false
}) => {
  var _a, _b, _c, _d, _e;
  const labels = useLabels();
  const blocks = useMemo(
    () => dedupeSettlementSources({
      eventDescription,
      marketDescription,
      primaryRules
    }),
    [eventDescription, marketDescription, primaryRules]
  );
  const settlementDifferences = useMemo(
    () => prepareSettlementDifferences(settlementDiff == null ? void 0 : settlementDiff.differences),
    [settlementDiff == null ? void 0 : settlementDiff.differences]
  );
  const eventBlock = (_a = blocks.find((block) => block.key === "eventDescription")) != null ? _a : null;
  const marketBlock = (_b = blocks.find((block) => block.key === "marketDescription")) != null ? _b : null;
  const primaryRulesBlock = (_c = blocks.find((block) => block.key === "primaryRules")) != null ? _c : null;
  const venueRuleBlocks = useMemo(
    () => buildSettlementVenueRules({
      eventBlock,
      marketBlock,
      primaryRulesBlock,
      settlementVenueRules
    }),
    [eventBlock, marketBlock, primaryRulesBlock, settlementVenueRules]
  );
  const defaultOpenDifferenceKey = (_e = (_d = settlementDifferences[0]) == null ? void 0 : _d.canonicalKey) != null ? _e : null;
  const [openDifferenceKeys, setOpenDifferenceKeys] = useState(
    () => defaultOpenDifferenceKey ? [defaultOpenDifferenceKey] : []
  );
  useEffect(() => {
    setOpenDifferenceKeys(defaultOpenDifferenceKey ? [defaultOpenDifferenceKey] : []);
  }, [defaultOpenDifferenceKey]);
  const handleToggleDifference = (canonicalKey) => {
    setOpenDifferenceKeys(
      (currentKeys) => currentKeys.includes(canonicalKey) ? currentKeys.filter((currentKey) => currentKey !== canonicalKey) : [...currentKeys, canonicalKey]
    );
  };
  if (isLoading) {
    return /* @__PURE__ */ jsx2(
      Skeleton,
      {
        ariaLabel: labels.trading.settlementLoading,
        className,
        view: skeletonViews.settlement
      }
    );
  }
  const resolvedSectionLabel = sectionLabel === defaultSettlementSectionLabel ? labels.trading.settlementSection : sectionLabel;
  if (settlementDifferences.length > 0) {
    return /* @__PURE__ */ jsxs2(
      Card,
      {
        id,
        className: cn(
          "group/agg-settlement-card",
          "flex w-full flex-col items-start gap-4 rounded-agg-xl border border-agg-separator bg-agg-secondary p-5 shadow-none hover:shadow-none sm:gap-5",
          className
        ),
        children: [
          /* @__PURE__ */ jsxs2("div", { className: "agg-settlement-header flex w-full flex-col items-start gap-1 text-agg-muted-foreground sm:flex-row sm:items-center sm:justify-between sm:gap-4", children: [
            /* @__PURE__ */ jsx2("p", { className: "shrink-0 text-agg-xs font-agg-bold leading-agg-4 uppercase", children: resolvedSectionLabel }),
            question ? /* @__PURE__ */ jsx2("p", { className: "agg-settlement-question min-w-0 text-agg-sm font-agg-normal leading-agg-5 sm:max-w-[314px] sm:truncate", children: question }) : null
          ] }),
          /* @__PURE__ */ jsxs2("div", { className: "agg-settlement-differences flex w-full flex-col items-start gap-5", children: [
            /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-2", children: [
              /* @__PURE__ */ jsx2("p", { className: "text-agg-sm font-agg-bold leading-agg-5 text-agg-foreground", children: "Key differences" }),
              /* @__PURE__ */ jsx2("span", { className: "flex size-4 shrink-0 items-center justify-center rounded-agg-full bg-agg-primary text-[10px] font-agg-bold leading-[14px] text-agg-on-primary", children: settlementDifferences.length })
            ] }),
            /* @__PURE__ */ jsx2("div", { className: "flex w-full flex-col items-start gap-5", children: settlementDifferences.map((difference) => {
              const venueKeys = resolveDifferenceVenueKeys(difference, settlementVenues);
              const isExpanded = openDifferenceKeys.includes(difference.canonicalKey) && venueKeys.length > 0;
              return /* @__PURE__ */ jsxs2(
                "div",
                {
                  id: getSettlementDifferenceId(id, difference.canonicalKey),
                  className: "agg-settlement-difference flex w-full flex-col items-start gap-2 rounded-agg-lg",
                  children: [
                    /* @__PURE__ */ jsxs2(
                      "button",
                      {
                        type: "button",
                        className: "flex w-full cursor-pointer items-start gap-2 text-left",
                        "aria-expanded": isExpanded,
                        onClick: () => handleToggleDifference(difference.canonicalKey),
                        children: [
                          /* @__PURE__ */ jsx2(
                            "i",
                            {
                              className: cn(
                                "fi",
                                resolveDifferenceIconClassName(difference.canonicalKey),
                                "inline-flex size-4! shrink-0 items-center justify-center text-[16px] leading-none text-agg-muted-foreground"
                              ),
                              "aria-hidden": "true"
                            }
                          ),
                          /* @__PURE__ */ jsx2("p", { className: "min-w-0 text-agg-sm font-agg-normal leading-agg-5 text-agg-foreground break-words [overflow-wrap:anywhere]", children: difference.title }),
                          /* @__PURE__ */ jsx2(
                            Icon,
                            {
                              name: isExpanded ? "chevron-up" : "chevron-down",
                              className: "size-4! mt-0.5 shrink-0 text-agg-foreground",
                              "aria-hidden": "true"
                            }
                          )
                        ]
                      }
                    ),
                    isExpanded ? /* @__PURE__ */ jsx2("dl", { className: "flex w-full flex-col items-start gap-1 px-6", children: venueKeys.map((venue) => {
                      var _a2;
                      const venueValue = (_a2 = difference.perVenue[venue]) != null ? _a2 : labels.trading.settlementValueUnavailable;
                      const venueLabel = resolveSettlementVenueLabel(venue, labels);
                      return /* @__PURE__ */ jsxs2("div", { className: "flex w-full items-start gap-2", children: [
                        /* @__PURE__ */ jsx2(
                          VenueLogo,
                          {
                            venue,
                            size: "small",
                            className: "mt-0.5 size-4",
                            ariaLabel: venueLabel
                          }
                        ),
                        /* @__PURE__ */ jsx2("dt", { className: "w-[88px] shrink-0 text-agg-sm font-agg-normal leading-agg-5 text-agg-foreground", children: venueLabel }),
                        /* @__PURE__ */ jsx2("dd", { className: "min-w-0 flex-1 text-agg-sm font-agg-normal leading-agg-5 text-agg-muted-foreground break-words [overflow-wrap:anywhere]", children: venueValue })
                      ] }, venue);
                    }) }) : null
                  ]
                },
                difference.canonicalKey
              );
            }) }),
            venueRuleBlocks.length > 0 ? /* @__PURE__ */ jsxs2(Fragment2, { children: [
              /* @__PURE__ */ jsx2("div", { className: "h-px w-full bg-agg-separator" }),
              /* @__PURE__ */ jsx2("p", { className: "text-agg-sm font-agg-bold leading-agg-5 text-agg-foreground", children: "Full rules by venue" }),
              /* @__PURE__ */ jsx2("div", { className: "flex w-full flex-col items-start gap-4", children: venueRuleBlocks.map((rule) => {
                const venueLabel = resolveSettlementVenueLabel(rule.venue, labels);
                return /* @__PURE__ */ jsxs2("details", { className: "group/agg-settlement-rule w-full", children: [
                  /* @__PURE__ */ jsxs2("summary", { className: "flex cursor-pointer list-none items-center gap-2 text-agg-sm font-agg-normal leading-agg-5 text-agg-foreground marker:hidden", children: [
                    /* @__PURE__ */ jsx2(
                      VenueLogo,
                      {
                        venue: rule.venue,
                        size: "small",
                        className: "size-4",
                        ariaLabel: venueLabel
                      }
                    ),
                    /* @__PURE__ */ jsx2("span", { children: venueLabel }),
                    /* @__PURE__ */ jsx2(
                      Icon,
                      {
                        name: "chevron-down",
                        className: "size-4! shrink-0 text-agg-foreground transition-transform group-open/agg-settlement-rule:rotate-180",
                        "aria-hidden": "true"
                      }
                    )
                  ] }),
                  /* @__PURE__ */ jsx2("div", { className: "mt-3 pl-6", children: /* @__PURE__ */ jsx2(SettlementTextRenderer, { content: rule.content }) })
                ] }, rule.venue);
              }) })
            ] }) : null
          ] })
        ]
      }
    );
  }
  return /* @__PURE__ */ jsxs2(
    Card,
    {
      id,
      className: cn(
        "group/agg-settlement-card",
        "flex flex-col w-full gap-5 rounded-agg-xl border border-agg-separator bg-agg-secondary p-5 shadow-none hover:shadow-none",
        className
      ),
      children: [
        /* @__PURE__ */ jsxs2("div", { className: cn("agg-settlement-header", getSettlementHeaderClassName()), children: [
          /* @__PURE__ */ jsx2("p", { className: "text-agg-xs font-agg-bold leading-agg-4 uppercase text-agg-muted-foreground", children: resolvedSectionLabel }),
          question ? /* @__PURE__ */ jsx2("p", { className: "agg-settlement-question text-agg-sm font-agg-bold leading-agg-5 text-agg-foreground", children: question }) : null
        ] }),
        blocks.length === 0 && settlementDifferences.length === 0 ? /* @__PURE__ */ jsx2("p", { className: "agg-settlement-empty text-agg-sm leading-agg-5 text-agg-muted-foreground", children: labels.trading.settlementEmpty }) : /* @__PURE__ */ jsxs2("div", { className: "agg-settlement-sections flex flex-col gap-4", children: [
          eventBlock || marketBlock ? /* @__PURE__ */ jsxs2(
            "div",
            {
              className: "agg-settlement-section agg-settlement-section-description",
              "data-source": "description",
              children: [
                eventBlock ? /* @__PURE__ */ jsx2("div", { "data-source": "eventDescription", children: /* @__PURE__ */ jsx2(SettlementTextRenderer, { content: eventBlock.content }) }) : null,
                eventBlock && marketBlock ? /* @__PURE__ */ jsx2("hr", { className: "agg-settlement-divider my-4 border-0 border-t border-agg-separator" }) : null,
                marketBlock ? /* @__PURE__ */ jsx2("div", { "data-source": "marketDescription", children: /* @__PURE__ */ jsx2(SettlementTextRenderer, { content: marketBlock.content }) }) : null
              ]
            }
          ) : null,
          primaryRulesBlock ? /* @__PURE__ */ jsxs2(
            "div",
            {
              className: "agg-settlement-section agg-settlement-section-primaryRules",
              "data-source": "primaryRules",
              children: [
                /* @__PURE__ */ jsx2("p", { className: "agg-settlement-section-label text-agg-xs font-agg-bold leading-agg-4 uppercase text-agg-muted-foreground mb-2", children: labels.trading.settlementPrimaryRulesLabel }),
                /* @__PURE__ */ jsx2(SettlementTextRenderer, { content: primaryRulesBlock.content })
              ]
            }
          ) : null
        ] })
      ]
    }
  );
};
Settlement.displayName = "Settlement";

// src/events/item-details/event-list-item-details.utils.ts
import dayjs2 from "dayjs";
var compareOutcomeSelectorLabels = (leftLabel, rightLabel) => {
  const leftSemanticLabel = toSemanticLabel(leftLabel);
  const rightSemanticLabel = toSemanticLabel(rightLabel);
  const binaryOrderByLabel = /* @__PURE__ */ new Map([
    ["yes", 0],
    ["no", 1]
  ]);
  const leftBinaryOrder = binaryOrderByLabel.get(leftSemanticLabel);
  const rightBinaryOrder = binaryOrderByLabel.get(rightSemanticLabel);
  if (leftBinaryOrder != null && rightBinaryOrder != null) {
    return leftBinaryOrder - rightBinaryOrder;
  }
  const leftDate = isDateLikeLabel(leftLabel) ? dayjs2(leftLabel).valueOf() : null;
  const rightDate = isDateLikeLabel(rightLabel) ? dayjs2(rightLabel).valueOf() : null;
  if (leftDate != null && rightDate != null && leftDate !== rightDate) {
    return leftDate - rightDate;
  }
  const parseNumericLabelValue = (value) => {
    const matchedValue = value.replace(/,/g, "").match(/-?\d+(\.\d+)?/);
    if (!matchedValue) return null;
    const parsedValue = Number(matchedValue[0]);
    return Number.isFinite(parsedValue) ? parsedValue : null;
  };
  const leftNumericValue = parseNumericLabelValue(leftLabel);
  const rightNumericValue = parseNumericLabelValue(rightLabel);
  if (leftNumericValue != null && rightNumericValue != null && leftNumericValue !== rightNumericValue) {
    return leftNumericValue - rightNumericValue;
  }
  return leftLabel.localeCompare(rightLabel, void 0, {
    numeric: true,
    sensitivity: "base"
  });
};
var sortOutcomeSelectorOutcomes = (outcomes) => {
  return [...outcomes].sort(
    (leftOutcome, rightOutcome) => compareOutcomeSelectorLabels(
      resolveOutcomeTitle(leftOutcome),
      resolveOutcomeTitle(rightOutcome)
    )
  );
};
var normalizeLabel = (value) => {
  return value.trim().toLowerCase().replace(/[_-]+/g, " ").replace(/[^\p{L}\p{N}\s]/gu, " ").replace(/\s+/g, " ");
};
var positiveOutcomeKeys = /* @__PURE__ */ new Set(["yes", "y", "true", "up", "buy", "long"]);
var negativeOutcomeKeys = /* @__PURE__ */ new Set(["no", "n", "false", "down", "sell", "short"]);
var toSemanticLabel = (value) => {
  const normalizedValue = normalizeLabel(value);
  if (positiveOutcomeKeys.has(normalizedValue)) return "yes";
  if (negativeOutcomeKeys.has(normalizedValue)) return "no";
  return normalizedValue;
};
var isDateLikeLabel = (value) => {
  if (!value.trim()) return false;
  return dayjs2(value).isValid();
};
var CHART_RANGE_PRIORITY = ["1H", "6H", "1D", "1W", "1M", "ALL"];
var RANGE_SECONDS_BY_TIME_RANGE = {
  "1H": 60 * 60,
  "6H": 6 * 60 * 60,
  "1D": 24 * 60 * 60,
  "1W": 7 * 24 * 60 * 60,
  "1M": 30 * 24 * 60 * 60,
  ALL: 6 * 30 * 24 * 60 * 60
};
var toUnixTimestamp = (value) => {
  if (!value) return null;
  const parsedValue = dayjs2(value);
  if (!parsedValue.isValid()) return null;
  return parsedValue.unix();
};
var isResolvedMarketStatus = (status) => {
  if (!status) return false;
  const normalizedStatus = status.trim().toLowerCase();
  return normalizedStatus.includes("resolved") || normalizedStatus.includes("closed") || normalizedStatus.includes("settled") || normalizedStatus.includes("final");
};
var resolveInitialEventDetailsChartRange = ({
  chartData,
  event,
  fallbackRange,
  nowSec = dayjs2().unix(),
  selectedMarket
}) => {
  var _a, _b;
  const scopedMarkets = selectedMarket ? [selectedMarket] : event.venueMarkets;
  const preferredEventStart = (_a = toUnixTimestamp(event.startDate)) != null ? _a : toUnixTimestamp(event.creationDate);
  const marketStartCandidates = scopedMarkets.map((market) => {
    var _a2;
    return (_a2 = toUnixTimestamp(market.startDate)) != null ? _a2 : toUnixTimestamp(market.creationDate);
  }).filter((value) => value != null);
  const metadataStarts = [preferredEventStart, ...marketStartCandidates].filter(
    (value) => value != null
  );
  const metadataEnds = [
    toUnixTimestamp(event.endDate),
    ...scopedMarkets.flatMap((market) => [
      toUnixTimestamp(market.endDate),
      toUnixTimestamp(market.resolutionDate)
    ])
  ].filter((value) => value != null);
  const historyTimestamps = chartData == null ? [] : Object.values(chartData.venues).flatMap((venueData) => [
    ...venueData.candles.map((candle) => candle.time),
    ...venueData.liveCandle ? [venueData.liveCandle.time] : []
  ]);
  const startCandidates = [...metadataStarts, ...historyTimestamps];
  if (startCandidates.length === 0) {
    return fallbackRange != null ? fallbackRange : null;
  }
  const marketResolved = [event.status, ...scopedMarkets.map((market) => market.status)].some(
    isResolvedMarketStatus
  );
  const isUsingSharedOverlapStart = scopedMarkets.length > 1 && marketStartCandidates.length === scopedMarkets.length;
  const startTs = isUsingSharedOverlapStart ? Math.max(...marketStartCandidates) : Math.min(...startCandidates);
  const endTs = Math.max(
    ...marketResolved && metadataEnds.length > 0 ? [nowSec, ...metadataEnds, ...historyTimestamps] : [nowSec, ...historyTimestamps]
  );
  const spanSeconds = Math.max(0, endTs - startTs);
  if (spanSeconds <= 0) {
    return fallbackRange != null ? fallbackRange : null;
  }
  if (!marketResolved && spanSeconds > RANGE_SECONDS_BY_TIME_RANGE["1M"]) {
    return "1M";
  }
  const requiredSeconds = spanSeconds * (isUsingSharedOverlapStart ? 1 : marketResolved ? 1.05 : 1.2);
  const matchingRange = CHART_RANGE_PRIORITY.find((range) => {
    return RANGE_SECONDS_BY_TIME_RANGE[range] >= requiredSeconds;
  });
  return (_b = matchingRange != null ? matchingRange : fallbackRange) != null ? _b : "ALL";
};
var matchOutcomeByLabel = (outcome, selectedOutcomeLabel) => {
  const normalizedSelectedLabel = normalizeLabel(selectedOutcomeLabel);
  const semanticSelectedLabel = toSemanticLabel(selectedOutcomeLabel);
  const candidates = [resolveOutcomeTitle(outcome), outcome.label, outcome.title].filter(
    (candidate) => typeof candidate === "string" && Boolean(candidate.trim())
  ).map(normalizeLabel);
  return candidates.some((candidate) => {
    return candidate === normalizedSelectedLabel || toSemanticLabel(candidate) === semanticSelectedLabel;
  });
};
var resolveOutcomesByVenue = (venueMarkets, selectedOutcomeLabel) => {
  return venueMarkets.map((market) => {
    const matchedOutcome = sortOutcomes(market.venueMarketOutcomes).find((outcome) => {
      return matchOutcomeByLabel(outcome, selectedOutcomeLabel);
    });
    if (!matchedOutcome) return null;
    return {
      venue: market.venue,
      market,
      outcome: matchedOutcome
    };
  }).filter((item) => item != null);
};
var resolveSeriesColor = (venue, index, isDarkTheme = false) => {
  var _a;
  const colorFromVenue = resolveVenueLineColor(venue, isDarkTheme);
  if (colorFromVenue) return colorFromVenue;
  return (_a = fallbackLineColors[index % fallbackLineColors.length]) != null ? _a : DEFAULT_VENUE_COLOR;
};
var toChartDisplayValue = (value, transformProbability) => {
  if (value == null || !Number.isFinite(value)) return void 0;
  return transformProbability(value) * 100;
};
var marketChartCandleToLineChartPoint = (candle, transformProbability) => {
  var _a, _b, _c, _d;
  const open = (_a = toChartDisplayValue(candle.open, transformProbability)) != null ? _a : 0;
  const high = (_b = toChartDisplayValue(candle.high, transformProbability)) != null ? _b : open;
  const low = (_c = toChartDisplayValue(candle.low, transformProbability)) != null ? _c : open;
  const close = (_d = toChartDisplayValue(candle.close, transformProbability)) != null ? _d : open;
  return {
    time: candle.time,
    value: close,
    open,
    high,
    low,
    close
  };
};
var marketChartCandleToScaledCandlePoint = (candle, transformProbability) => {
  var _a, _b, _c, _d;
  const point = marketChartCandleToLineChartPoint(candle, transformProbability);
  return {
    time: point.time,
    open: (_a = point.open) != null ? _a : point.value,
    high: (_b = point.high) != null ? _b : point.value,
    low: (_c = point.low) != null ? _c : point.value,
    close: (_d = point.close) != null ? _d : point.value,
    v: candle.volume
  };
};
var venueCandlesToLinePoints = (venueData, transformProbability) => {
  const candles = venueData.liveCandle && !venueData.candles.some((candle) => {
    var _a;
    return candle.time === ((_a = venueData.liveCandle) == null ? void 0 : _a.time);
  }) ? [...venueData.candles, venueData.liveCandle] : venueData.liveCandle ? venueData.candles.map(
    (candle) => {
      var _a;
      return candle.time === ((_a = venueData.liveCandle) == null ? void 0 : _a.time) ? venueData.liveCandle : candle;
    }
  ) : venueData.candles;
  return candles.map((candle) => marketChartCandleToLineChartPoint(candle, transformProbability));
};
var resolveMarketChartVenueSeries = ({
  chartData,
  transformProbability
}) => {
  if (!chartData) return [];
  return Object.entries(chartData.venues).map(([venue, venueData]) => ({
    venue,
    points: venueCandlesToLinePoints(venueData, transformProbability)
  })).filter((item) => item.points.length > 0);
};
var resolveAggregatedCandleSource = (candles) => {
  if (candles.some((candle) => candle.source === "trade")) return "trade";
  if (candles.some((candle) => candle.source === "ws")) return "ws";
  return "rest";
};
var aggregateMarketChartCandles = (candles) => {
  const candlesByTime = /* @__PURE__ */ new Map();
  candles.forEach((candle) => {
    var _a;
    const existingCandles = (_a = candlesByTime.get(candle.time)) != null ? _a : [];
    existingCandles.push(candle);
    candlesByTime.set(candle.time, existingCandles);
  });
  return [...candlesByTime.entries()].sort((left, right) => left[0] - right[0]).map(([time, timeCandles]) => {
    var _a, _b, _c, _d;
    const open = (_a = resolveAverageProbability(timeCandles.map((candle) => candle.open))) != null ? _a : 0;
    const high = (_b = resolveAverageProbability(timeCandles.map((candle) => candle.high))) != null ? _b : open;
    const low = (_c = resolveAverageProbability(timeCandles.map((candle) => candle.low))) != null ? _c : open;
    const close = (_d = resolveAverageProbability(timeCandles.map((candle) => candle.close))) != null ? _d : open;
    const volumeValues = timeCandles.map((candle) => candle.volume).filter((value) => value != null);
    return {
      time,
      open,
      high,
      low,
      close,
      volume: volumeValues.length > 0 ? volumeValues.reduce((sum, value) => sum + value, 0) : null,
      source: resolveAggregatedCandleSource(timeCandles)
    };
  });
};
var resolveChartVenueEntries = ({
  chartData,
  selectedVenue
}) => {
  if (!chartData) return [];
  const venueEntries = Object.entries(chartData.venues);
  if (!selectedVenue) return venueEntries;
  return venueEntries.filter(([venue]) => venue === selectedVenue);
};
var resolveMarketChartDisplaySeries = ({
  chartData,
  selectedVenue,
  transformProbability
}) => {
  const venueEntries = resolveChartVenueEntries({ chartData, selectedVenue });
  if (venueEntries.length === 0) return [];
  if (selectedVenue) {
    return venueEntries.map(([venue, venueData]) => ({
      venue,
      points: venueCandlesToLinePoints(venueData, transformProbability)
    })).filter((item) => item.points.length > 0);
  }
  const aggregatedCandles = aggregateMarketChartCandles(
    venueEntries.flatMap(([, venueData]) => {
      const closed = venueData.candles;
      if (!venueData.liveCandle) return closed;
      const hasOverlap = closed.some((candle) => {
        var _a;
        return candle.time === ((_a = venueData.liveCandle) == null ? void 0 : _a.time);
      });
      return hasOverlap ? closed.map(
        (candle) => {
          var _a;
          return candle.time === ((_a = venueData.liveCandle) == null ? void 0 : _a.time) ? venueData.liveCandle : candle;
        }
      ) : [...closed, venueData.liveCandle];
    })
  );
  if (aggregatedCandles.length === 0) return [];
  return [
    {
      venue: "aggregate",
      points: aggregatedCandles.map(
        (candle) => marketChartCandleToLineChartPoint(candle, transformProbability)
      )
    }
  ];
};
var resolveAverageProbability = (values) => {
  const validValues = values.filter((value) => value != null);
  if (validValues.length === 0) return void 0;
  return validValues.reduce((sum, value) => sum + value, 0) / validValues.length;
};
var resolveMarketChartLiveState = ({
  chartData,
  selectedVenue,
  transformProbability
}) => {
  var _a, _b;
  if (!chartData) {
    return {
      liveCandle: null,
      lineValue: void 0,
      live: false
    };
  }
  const venueEntries = selectedVenue ? Object.entries(chartData.venues).filter(([venue]) => venue === selectedVenue) : Object.entries(chartData.venues);
  if (venueEntries.length === 0) {
    return {
      liveCandle: null,
      lineValue: void 0,
      live: false
    };
  }
  if (selectedVenue) {
    const selectedVenueData = (_a = venueEntries[0]) == null ? void 0 : _a[1];
    const lineValue2 = (selectedVenueData == null ? void 0 : selectedVenueData.lineValue) != null ? toChartDisplayValue(selectedVenueData.lineValue, transformProbability) : void 0;
    return {
      liveCandle: (selectedVenueData == null ? void 0 : selectedVenueData.liveCandle) ? marketChartCandleToScaledCandlePoint(selectedVenueData.liveCandle, transformProbability) : null,
      lineValue: lineValue2,
      live: (selectedVenueData == null ? void 0 : selectedVenueData.liveCandle) != null
    };
  }
  const liveCandles = aggregateMarketChartCandles(
    venueEntries.flatMap(([, venueData]) => venueData.liveCandle ? [venueData.liveCandle] : [])
  );
  const aggregatedLiveCandle = (_b = liveCandles[liveCandles.length - 1]) != null ? _b : null;
  const primaryLineValue = resolveAverageProbability(
    venueEntries.map(([, venueData]) => venueData.lineValue)
  );
  const lineValue = primaryLineValue != null ? toChartDisplayValue(primaryLineValue, transformProbability) : void 0;
  return {
    liveCandle: aggregatedLiveCandle ? marketChartCandleToScaledCandlePoint(aggregatedLiveCandle, transformProbability) : null,
    lineValue,
    live: aggregatedLiveCandle != null
  };
};

// src/events/market-details/market-details.utils.ts
import { safeParse as safeParse2 } from "@agg-build/sdk";
import dayjs3 from "dayjs";
var VALID_TABS = /* @__PURE__ */ new Set(["order-book", "graph", "other"]);
var isMarketDetailsTab = (v) => typeof v === "string" && VALID_TABS.has(v);
var normalizeLabel2 = (value) => {
  return value.trim().toLowerCase();
};
var hasBinaryLabels = (labels) => {
  const normalizedLabels = labels.map(normalizeLabel2);
  return normalizedLabels.includes("yes") && normalizedLabels.includes("no");
};
var resolveInitialTab = (defaultTab) => {
  const parsedTab = safeParse2(defaultTab, isMarketDetailsTab);
  if (parsedTab.success) return parsedTab.data;
  return "order-book";
};
var resolveMarketFromVenueMarkets = (venueMarkets, marketId) => {
  var _a, _b, _c, _d, _e, _f;
  if (!venueMarkets || venueMarkets.length === 0) return void 0;
  if (!marketId) {
    const normalizedVenueMarkets = normalizeVenueMarketCluster(venueMarkets);
    const primary = selectPrimaryVenueMarket(normalizedVenueMarkets);
    const totalVolume2 = normalizedVenueMarkets.reduce((sum, vm) => {
      return sum + (typeof vm.volume === "number" ? vm.volume : 0);
    }, 0);
    return {
      id: (_c = (_b = primary == null ? void 0 : primary.id) != null ? _b : (_a = normalizedVenueMarkets[0]) == null ? void 0 : _a.id) != null ? _c : venueMarkets[0].id,
      venueMarkets: normalizedVenueMarkets,
      volume: totalVolume2 || (primary == null ? void 0 : primary.volume),
      status: primary == null ? void 0 : primary.status,
      startDate: primary == null ? void 0 : primary.startDate,
      endDate: primary == null ? void 0 : primary.endDate,
      creationDate: primary == null ? void 0 : primary.creationDate,
      question: (_f = (_e = primary == null ? void 0 : primary.question) != null ? _e : (_d = normalizedVenueMarkets[0]) == null ? void 0 : _d.question) != null ? _f : venueMarkets[0].question
    };
  }
  const matchedVenueMarket = normalizeVenueMarketCluster(venueMarkets).find(
    (vm) => vm.id === marketId || vm.externalIdentifier === marketId
  );
  if (!matchedVenueMarket) return void 0;
  const siblingVenueMarkets = normalizeVenueMarketCluster(venueMarkets, matchedVenueMarket.id);
  const totalVolume = siblingVenueMarkets.reduce((sum, vm) => {
    return sum + (typeof vm.volume === "number" ? vm.volume : 0);
  }, 0);
  return {
    id: matchedVenueMarket.id,
    venueMarkets: siblingVenueMarkets,
    volume: totalVolume || matchedVenueMarket.volume,
    status: matchedVenueMarket.status,
    startDate: matchedVenueMarket.startDate,
    endDate: matchedVenueMarket.endDate,
    creationDate: matchedVenueMarket.creationDate,
    question: matchedVenueMarket.question
  };
};
var resolveDisplayOutcomeLabels = (labels) => {
  if (!hasBinaryLabels(labels)) return labels;
  return ["Yes", "No"].filter(
    (label) => labels.some((value) => normalizeLabel2(value) === normalizeLabel2(label))
  );
};
var TRAILING_LINE_VALUE_PATTERN = /^(.*?)(\s+[+-]?\d+(?:\.\d+)?)$/;
var resolveLineOutcomeDisplayParts = (label, title) => {
  var _a, _b;
  const sourceText = (title == null ? void 0 : title.trim()) || label.trim();
  const match = TRAILING_LINE_VALUE_PATTERN.exec(sourceText);
  if (!match) {
    return {
      title: (title == null ? void 0 : title.trim()) || null,
      lineLabel: null
    };
  }
  const baseTitle = ((_a = match[1]) == null ? void 0 : _a.trim()) || null;
  const lineLabel = ((_b = match[2]) == null ? void 0 : _b.trim()) || null;
  return {
    title: baseTitle,
    lineLabel
  };
};
var formatScopedLineValue = (value) => {
  return Number.isInteger(value) ? String(value) : value.toFixed(1);
};
var resolveScopedMarketLineLabel = ({
  outcomeIndex,
  scopedMarket
}) => {
  var _a;
  const lineValue = scopedMarket == null ? void 0 : scopedMarket.lineValue;
  if (lineValue == null) return null;
  const sportsMarketType = normalizeLabel2((_a = scopedMarket == null ? void 0 : scopedMarket.sportsMarketType) != null ? _a : "");
  if (sportsMarketType === "spread") {
    const directionalLineValue = outcomeIndex === 0 ? lineValue : lineValue * -1;
    const prefix = directionalLineValue > 0 ? "+" : "";
    return `${prefix}${formatScopedLineValue(directionalLineValue)}`;
  }
  return formatScopedLineValue(lineValue);
};
var resolveMarketDetailsOutcomeLabels = (venueMarkets) => {
  var _a;
  const primaryMarket = selectPrimaryVenueMarket(venueMarkets);
  const labels = /* @__PURE__ */ new Map();
  const upsertOutcome = (outcome) => {
    var _a2;
    const label = outcome.label.trim();
    if (!label) return;
    const key = normalizeLabel2(label);
    const title = outcome.title ? (_a2 = outcome.title) == null ? void 0 : _a2.trim() : null;
    const existing = labels.get(key);
    if (!existing) {
      labels.set(key, { label, title });
      return;
    }
    if (existing.title == null && title != null) {
      labels.set(key, __spreadProps(__spreadValues({}, existing), { title }));
    }
  };
  ((_a = primaryMarket == null ? void 0 : primaryMarket.venueMarketOutcomes) != null ? _a : []).forEach(upsertOutcome);
  venueMarkets.forEach((market) => sortOutcomes(market.venueMarketOutcomes).forEach(upsertOutcome));
  return [...labels.values()];
};
var resolveInitialOutcomeLabel = (labels, defaultOutcomeLabel) => {
  var _a;
  if (labels.length === 0) return void 0;
  if (defaultOutcomeLabel) {
    const matchedLabel = labels.find(
      (label) => normalizeLabel2(label) === normalizeLabel2(defaultOutcomeLabel)
    );
    if (matchedLabel) return matchedLabel;
  }
  if (hasBinaryLabels(labels)) {
    return (_a = labels.find((label) => normalizeLabel2(label) === "yes")) != null ? _a : labels[0];
  }
  return labels[0];
};
var resolveScopedSelectedOutcome = ({
  venueMarkets,
  selectedOutcomeId,
  defaultOutcomeLabel,
  suppressFallbackWhenSelectedOutcomeOutOfScope
}) => {
  var _a, _b;
  if (selectedOutcomeId) {
    const matchingOutcome = venueMarkets.flatMap((market) => market.venueMarketOutcomes).find((outcome) => outcome.id === selectedOutcomeId);
    if (matchingOutcome) {
      return {
        outcomeId: matchingOutcome.id,
        outcomeLabel: matchingOutcome.label
      };
    }
  }
  if (suppressFallbackWhenSelectedOutcomeOutOfScope) {
    return {
      outcomeId: null,
      outcomeLabel: void 0
    };
  }
  const outcomeLabels = resolveDisplayOutcomeLabels(
    resolveMarketDetailsOutcomeLabels(venueMarkets).map((outcome) => outcome.label)
  );
  const outcomeLabel = resolveInitialOutcomeLabel(outcomeLabels, defaultOutcomeLabel);
  const outcomeId = outcomeLabel ? (_b = (_a = resolveOutcomesByVenue(venueMarkets, outcomeLabel)[0]) == null ? void 0 : _a.outcome.id) != null ? _b : null : null;
  return {
    outcomeId,
    outcomeLabel
  };
};
var resolveAverageProbabilityByLabel = (venueMarkets, labels) => {
  return new Map(
    labels.map((label) => {
      const matchingOutcomes = resolveOutcomesByVenue(venueMarkets, label);
      const probabilities = matchingOutcomes.map((item) => normalizeProbability(item.outcome.price)).filter((value) => value != null);
      if (!probabilities.length) {
        return [label, void 0];
      }
      const averageProbability = probabilities.reduce((sum, value) => sum + value, 0) / probabilities.length;
      return [label, averageProbability];
    })
  );
};
var formatProbabilityPercent = (value, formatPercent) => {
  return formatMarketProbabilityPercent(value, formatPercent);
};
var resolveOutcomeTone = (label, index) => {
  const normalizedLabel = normalizeLabel2(label);
  if (normalizedLabel === "yes" || normalizedLabel === "up" || normalizedLabel === "buy") {
    return "positive";
  }
  if (normalizedLabel === "no" || normalizedLabel === "down" || normalizedLabel === "sell") {
    return "negative";
  }
  return index === 0 ? "positive" : "negative";
};
var resolveHeaderOutcomeItems = (venueMarkets, scopedMarket, variant) => {
  const outcomes = resolveMarketDetailsOutcomeLabels(venueMarkets);
  const labels = resolveDisplayOutcomeLabels(outcomes.map((outcome) => outcome.label));
  const probabilityByLabel = resolveAverageProbabilityByLabel(venueMarkets, labels);
  return labels.map((label, index) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
    const scopedOutcome = (_a = scopedMarket == null ? void 0 : scopedMarket.venueMarketOutcomes) == null ? void 0 : _a.find(
      (outcome) => normalizeLabel2(outcome.label) === normalizeLabel2(label)
    );
    const scopedTitle = ((_b = scopedOutcome == null ? void 0 : scopedOutcome.title) == null ? void 0 : _b.trim()) || null;
    const fallbackTitle = (_d = (_c = outcomes.find((outcome) => normalizeLabel2(outcome.label) === normalizeLabel2(label))) == null ? void 0 : _c.title) != null ? _d : null;
    const resolvedTitle = scopedOutcome ? scopedTitle : fallbackTitle;
    const lineDisplayParts = variant === "line" ? resolveLineOutcomeDisplayParts(label, resolvedTitle) : { title: resolvedTitle, lineLabel: null };
    const fallbackLineLabel = variant === "line" ? resolveScopedMarketLineLabel({
      outcomeIndex: index,
      scopedMarket
    }) : null;
    const sportsMarketType = normalizeLabel2((_e = scopedMarket == null ? void 0 : scopedMarket.sportsMarketType) != null ? _e : "");
    const fallbackOutcomeByVenue = resolveOutcomesByVenue(venueMarkets, label)[0];
    const outcomeId = (_g = (_f = scopedOutcome == null ? void 0 : scopedOutcome.id) != null ? _f : fallbackOutcomeByVenue == null ? void 0 : fallbackOutcomeByVenue.outcome.id) != null ? _g : "";
    const venue = (_k = (_j = (_h = scopedMarket == null ? void 0 : scopedMarket.venue) != null ? _h : fallbackOutcomeByVenue == null ? void 0 : fallbackOutcomeByVenue.venue) != null ? _j : (_i = venueMarkets[0]) == null ? void 0 : _i.venue) != null ? _k : "polymarket";
    return {
      title: lineDisplayParts.title,
      id: outcomeId,
      venue,
      label,
      lineLabel: sportsMarketType === "total" ? fallbackLineLabel != null ? fallbackLineLabel : lineDisplayParts.lineLabel : (_l = lineDisplayParts.lineLabel) != null ? _l : fallbackLineLabel,
      probability: probabilityByLabel.get(label),
      tone: resolveOutcomeTone(label, index),
      variant
    };
  });
};
var resolveSubtitle = ({
  venueMarkets,
  volume,
  formatCompactCurrency,
  labels
}) => {
  const { venueCount } = getVenueSummary(venueMarkets);
  const parts = [
    `${venueCount} ${venueCount === 1 ? labels.marketDetails.meta.venueSingular : labels.marketDetails.meta.venuePlural}`
  ];
  if (typeof volume === "number" && volume > 0) {
    parts.push(`${formatCompactCurrency(volume)} ${labels.marketDetails.meta.volumeSuffix}`);
  }
  return parts.join(" \xB7 ");
};
var resolveOtherTabRows = (market, labels) => {
  var _a;
  const rows = [];
  rows.push({
    label: labels.marketDetails.meta.status,
    value: (_a = market.status) != null ? _a : labels.marketDetails.meta.unknown
  });
  if (market.creationDate) {
    rows.push({
      label: labels.marketDetails.meta.created,
      value: dayjs3(market.creationDate).format("MMM D, YYYY")
    });
  }
  if (market.startDate) {
    rows.push({
      label: labels.marketDetails.meta.opens,
      value: dayjs3(market.startDate).format("MMM D, YYYY")
    });
  }
  if (market.endDate) {
    rows.push({
      label: labels.marketDetails.meta.closes,
      value: dayjs3(market.endDate).format("MMM D, YYYY")
    });
  }
  if (rows.length === 1) {
    rows.push({
      label: labels.marketDetails.meta.markets,
      value: `${market.venueMarkets.length}`
    });
  }
  return rows;
};
var buildMarketDetailsModel = ({
  venueMarkets,
  marketId,
  title,
  image,
  formatCompactCurrency,
  labels
}) => {
  var _a, _b, _c, _d;
  const market = resolveMarketFromVenueMarkets(venueMarkets, marketId);
  if (!market) return void 0;
  const primaryVenueMarket = selectPrimaryVenueMarket(market.venueMarkets);
  if (!primaryVenueMarket) return void 0;
  const scopedVenueMarket = (_a = market.venueMarkets.find((venueMarket) => venueMarket.id === market.id)) != null ? _a : primaryVenueMarket;
  const resolvedTitle = (title == null ? void 0 : title.trim()) || scopedVenueMarket.question || market.question || primaryVenueMarket.question;
  const resolvedImage = (_c = (_b = typeof image === "string" && image.trim() ? image : void 0) != null ? _b : typeof scopedVenueMarket.image === "string" && scopedVenueMarket.image.trim() ? scopedVenueMarket.image : void 0) != null ? _c : typeof primaryVenueMarket.image === "string" && primaryVenueMarket.image.trim() ? primaryVenueMarket.image : void 0;
  const resolvedVolume = typeof market.volume === "number" ? market.volume : (_d = primaryVenueMarket.volume) != null ? _d : void 0;
  const subtitle = resolveSubtitle({
    venueMarkets: market.venueMarkets,
    volume: resolvedVolume,
    formatCompactCurrency,
    labels
  });
  const outcomeLabels = resolveDisplayOutcomeLabels(
    resolveMarketDetailsOutcomeLabels(market.venueMarkets).map((outcome) => outcome.label)
  );
  const probabilityByLabel = resolveAverageProbabilityByLabel(market.venueMarkets, outcomeLabels);
  return {
    market,
    primaryVenueMarket,
    title: resolvedTitle,
    image: resolvedImage,
    subtitle,
    outcomeLabels,
    probabilityByLabel
  };
};

// src/events/shared/display-reference-price.ts
var getDisplayReferencePrice = ({
  bestMidpoint,
  fallbackPrice
}) => {
  var _a;
  return (_a = bestMidpoint != null ? bestMidpoint : fallbackPrice) != null ? _a : void 0;
};

// src/events/shared/select-outcome-price.ts
var selectOutcomePrice = ({
  outcomeId,
  selection,
  bestPrices,
  bestMidpointsByOutcomeId,
  livePrices,
  fallbackPrice
}) => {
  var _a, _b;
  if (!outcomeId) return void 0;
  if (selection === "buy") {
    const bestAsk = (_a = bestPrices == null ? void 0 : bestPrices.get(outcomeId)) == null ? void 0 : _a.bestAsk;
    if (bestAsk != null) return bestAsk;
  } else if (selection === "sell") {
    const bestBid = (_b = bestPrices == null ? void 0 : bestPrices.get(outcomeId)) == null ? void 0 : _b.bestBid;
    if (bestBid != null) return bestBid;
  }
  const livePrice = livePrices == null ? void 0 : livePrices.get(outcomeId);
  if (livePrice != null) return livePrice;
  const midpointPrice = bestMidpointsByOutcomeId == null ? void 0 : bestMidpointsByOutcomeId.get(outcomeId);
  if (midpointPrice != null) return midpointPrice;
  return fallbackPrice != null ? fallbackPrice : void 0;
};

// src/events/shared/display-outcome-price.ts
var normalizeOutcomeLabel = (label) => {
  return typeof label === "string" ? label.trim().toLowerCase() : "";
};
var getDisplayOutcomePrice = ({
  outcomeId,
  outcomeLabel,
  selection,
  bestPrices,
  bestMidpoint,
  bestMidpointsByOutcomeId,
  livePrices,
  fallbackPrice
}) => {
  var _a;
  if (selection && outcomeId) {
    return selectOutcomePrice({
      outcomeId,
      selection,
      bestPrices,
      bestMidpointsByOutcomeId,
      livePrices,
      fallbackPrice
    });
  }
  const livePrice = outcomeId ? livePrices == null ? void 0 : livePrices.get(outcomeId) : void 0;
  if (livePrice != null) return livePrice;
  const bestOutcomePrice = outcomeId ? bestMidpointsByOutcomeId == null ? void 0 : bestMidpointsByOutcomeId.get(outcomeId) : void 0;
  const resolvedFallbackPrice = (_a = bestOutcomePrice != null ? bestOutcomePrice : fallbackPrice) != null ? _a : void 0;
  if (normalizeOutcomeLabel(outcomeLabel) === "yes") {
    return getDisplayReferencePrice({
      bestMidpoint,
      fallbackPrice: resolvedFallbackPrice
    });
  }
  return resolvedFallbackPrice;
};

// src/events/shared/event-trading-state.utils.ts
import dayjs4 from "dayjs";
var formatTradingStateDate = (value) => {
  if (!dayjs4(value).isValid()) return value;
  return dayjs4(value).format("MMM D, YYYY");
};
var resolveTradingStateTimestampLabel = (labels, state) => {
  if (state.kind === "resolved" && state.resolvesAt) {
    return labels.eventMarketPage.resolvedAt(formatTradingStateDate(state.resolvesAt));
  }
  if (state.kind === "closed" && state.endsAt) {
    return labels.eventMarketPage.closedAt(formatTradingStateDate(state.endsAt));
  }
  if (state.kind === "unopened" && state.startsAt) {
    return labels.eventMarketPage.opensAt(formatTradingStateDate(state.startsAt));
  }
  return null;
};
var resolveTradingStatePresentation = (labels, state) => {
  var _a;
  const timestampLabel = resolveTradingStateTimestampLabel(labels, state);
  const resolvedOutcomeLabel = resolveResolvedOutcomeLabel({
    market: (_a = state.market) != null ? _a : null,
    outcome: state.winningOutcome
  });
  const winningOutcomeLabel = resolvedOutcomeLabel ? labels.eventMarketPage.winningOutcome(resolvedOutcomeLabel) : null;
  if (state.kind === "resolved") {
    return {
      badgeLabel: labels.eventMarketPage.tradingResolvedBadge,
      title: labels.eventMarketPage.tradingResolvedTitle,
      description: labels.eventMarketPage.tradingResolvedDescription,
      iconName: "check-circle",
      timestampLabel,
      winningOutcomeLabel
    };
  }
  if (state.kind === "paused") {
    return {
      badgeLabel: labels.eventMarketPage.tradingPausedBadge,
      title: labels.eventMarketPage.tradingPausedTitle,
      description: labels.eventMarketPage.tradingPausedDescription,
      iconName: "warning-filled",
      timestampLabel,
      winningOutcomeLabel
    };
  }
  if (state.kind === "unopened") {
    return {
      badgeLabel: labels.eventMarketPage.tradingUnopenedBadge,
      title: labels.eventMarketPage.tradingUnopenedTitle,
      description: labels.eventMarketPage.tradingUnopenedDescription,
      iconName: "info",
      timestampLabel,
      winningOutcomeLabel
    };
  }
  if (state.kind === "closed") {
    return {
      badgeLabel: labels.eventMarketPage.tradingClosedBadge,
      title: labels.eventMarketPage.tradingClosedTitle,
      description: labels.eventMarketPage.tradingClosedDescription,
      iconName: "warning-filled",
      timestampLabel,
      winningOutcomeLabel
    };
  }
  return {
    badgeLabel: labels.eventMarketPage.tradingUnavailableBadge,
    title: labels.eventMarketPage.tradingUnavailableTitle,
    description: labels.eventMarketPage.tradingUnavailableDescription,
    iconName: "info",
    timestampLabel,
    winningOutcomeLabel
  };
};
var resolveTradingStateBadgeClassName = (kind) => {
  if (kind === "resolved") {
    return "border-agg-success/20 bg-agg-success/10 text-agg-success";
  }
  if (kind === "unopened") {
    return "border-agg-primary/15 bg-agg-primary/5 text-agg-primary";
  }
  if (kind === "paused") {
    return "border-agg-warning/20 bg-agg-warning/10 text-agg-warning";
  }
  if (kind === "closed") {
    return "border-agg-warning/20 bg-agg-warning/10 text-agg-warning";
  }
  return "border-agg-separator bg-agg-secondary text-agg-muted-foreground";
};
var ORDER_ELIGIBILITY_LABEL_MAP = {
  no_event_selected: (labels) => labels.trading.orderDisabledNoEvent,
  no_market_selected: (labels) => labels.trading.orderDisabledNoMarket,
  no_outcome_selected: (labels) => labels.trading.orderDisabledNoOutcome,
  event_resolved: (labels) => labels.trading.orderDisabledEventResolved,
  event_closed: (labels) => labels.trading.orderDisabledEventClosed,
  event_paused: (labels) => labels.trading.orderDisabledEventPaused,
  event_unopened: (labels) => labels.trading.orderDisabledEventUnopened,
  event_unavailable: (labels) => labels.trading.orderDisabledEventUnavailable,
  market_resolved: (labels) => labels.trading.orderDisabledMarketResolved,
  market_closed: (labels) => labels.trading.orderDisabledMarketClosed,
  market_paused: (labels) => labels.trading.orderDisabledMarketPaused,
  market_unopened: (labels) => labels.trading.orderDisabledMarketUnopened,
  market_unavailable: (labels) => labels.trading.orderDisabledMarketUnavailable
};
var resolveOrderEligibilityMessage = (labels, reason) => {
  if (reason === "eligible") return null;
  return ORDER_ELIGIBILITY_LABEL_MAP[reason](labels);
};

export {
  useEventTradingContext,
  sortOutcomeSelectorOutcomes,
  resolveInitialEventDetailsChartRange,
  resolveOutcomesByVenue,
  resolveSeriesColor,
  resolveMarketChartVenueSeries,
  resolveMarketChartDisplaySeries,
  resolveMarketChartLiveState,
  formatProbabilityCents,
  resolveOrderBookRows,
  resolveUnifiedOrderBookEntries,
  resolveInitialTab,
  resolveMarketFromVenueMarkets,
  resolveInitialOutcomeLabel,
  resolveScopedSelectedOutcome,
  formatProbabilityPercent,
  resolveHeaderOutcomeItems,
  resolveOtherTabRows,
  buildMarketDetailsModel,
  getDisplayOutcomePrice,
  defaultSettlementSectionLabel,
  defaultTradingDisclaimer,
  getTradingDateLabel,
  getTradingVenueLabel,
  getTradingValueLabel,
  getTradingPriceLabel,
  getTradingAveragePriceLabel,
  getTradingBalanceLabel,
  getTradingSharesLabel,
  getTradingSlippageLabel,
  getFirstSettlementParagraph,
  SETTLEMENT_SECTION_ID,
  getSettlementDifferenceId,
  prepareSettlementDifferences,
  resolveDifferenceIconClassName,
  Settlement,
  resolveTradingStatePresentation,
  resolveTradingStateBadgeClassName,
  resolveOrderEligibilityMessage
};
