The Panel

Torn City loss marketplace sidebar - buy and sell losses.

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(Tôi đã có Trình quản lý tập lệnh người dùng, hãy cài đặt nó!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

// ==UserScript==
// @name         The Panel
// @namespace    https://torn-the-panel.vercel.app/
// @version      0.3.13
// @description  Torn City loss marketplace sidebar - buy and sell losses.
// @author       ARCANE [2297468]
// @license      All Rights Reserved
// @match        https://www.torn.com/*
// @match        https://torn.com/*
// @run-at       document-idle
// @grant        GM.getValue
// @grant        GM.setValue
// @grant        GM.deleteValue
// @grant        GM.registerMenuCommand
// @grant        GM.unregisterMenuCommand
// @grant        GM.xmlHttpRequest
// @require      https://cdn.jsdelivr.net/npm/@supabase/[email protected]/dist/umd/supabase.js#sha256-ZsSa1mHmXYMrbdjAoRyfTlHRIq8bVjWzCrjyA8BIFXU=
// @connect      cqqqkbhzmdxasgtyqbwg.supabase.co
// @connect      api.torn.com
// @connect      127.0.0.1
// @connect      localhost
// @connect      torn.com
// @connect      www.torn.com
// @compatible   firefox Requires a userscript manager.
// @compatible   chrome Requires a userscript manager.
// @compatible   safari Requires a userscript manager.
// @homepageURL   https://torn-the-panel.vercel.app/
// @supportURL    https://www.torn.com/messages.php#/p=compose&XID=2297468
// ==/UserScript==
var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
(function(supabaseJs) {
  "use strict";
  var _a;
  let configuredRuntime = null;
  function configurePlatformRuntime(runtime) {
    configuredRuntime = runtime;
  }
  function getPlatformRuntime() {
    if (!configuredRuntime) {
      throw new Error("Platform runtime has not been configured.");
    }
    return configuredRuntime;
  }
  function isWebPlatform() {
    return (configuredRuntime == null ? void 0 : configuredRuntime.name) === "web";
  }
  const version = "0.3.13";
  const packageJson = {
    version
  };
  const BRAND_NAME = "The Panel";
  const APP_VERSION = packageJson.version;
  const SITE_BASE_URL = "https://torn-the-panel.vercel.app";
  const BRAND_NAME_TORN_API = "ThePanel";
  const BRAND_LOG_PREFIX = "[The Panel]";
  const FEATURE_RECONNECT_API_KEY_MESSAGE = 'A new update has been made. Log out, then reconnect with a new key using the "Create API Key" Button.';
  function getFeatureReconnectApiKeyMessage(causes) {
    const reasons = [];
    if (causes.itemMarket) {
      reasons.push("missing market → itemmarket access for Xanax pricing");
    }
    if (causes.itemReceiveLog) {
      reasons.push("missing Item receive logs (log category 61)");
    }
    if (causes.equipment) {
      reasons.push("missing user → equipment access");
    }
    if (reasons.length === 0) return FEATURE_RECONNECT_API_KEY_MESSAGE;
    return `${FEATURE_RECONNECT_API_KEY_MESSAGE} (${reasons.join("; ")})`;
  }
  const CREATE_API_KEY_URL = `https://www.torn.com/preferences.php#tab=api?step=addNewKey&title=${BRAND_NAME_TORN_API}&user=basic,equipment,perks,attacks,log&faction=basic&market=itemmarket&logIds=157,181,85,61,153,154`;
  const PRIVACY_POLICY_URL = `${SITE_BASE_URL}/privacy.html`;
  const CHROME_WEB_STORE_URL = "https://chromewebstore.google.com/detail/pndmjeeflojkfglnhpbljlhlpfjcdhhb?utm_source=item-share-cb";
  const GREASY_FORK_URL = "https://greasyfork.org/en/scripts/579752-buy-losses-now";
  const SUPPORT_URL = "https://www.torn.com/messages.php#/p=compose&XID=2297468";
  const BRAND_GRADIENT = "linear-gradient(180deg, #708bdb 0%, #3f43cf 100%)";
  function applyBrandButtonBackground(button2) {
    button2.style.setProperty("background", BRAND_GRADIENT, "important");
    button2.style.setProperty("background-image", BRAND_GRADIENT, "important");
  }
  function normalizeSupabaseUrl(raw) {
    return raw.trim().replace(/\/rest\/v1\/?$/i, "").replace(/\/+$/, "");
  }
  const SUPABASE_URL = normalizeSupabaseUrl(
    "https://cqqqkbhzmdxasgtyqbwg.supabase.co"
  );
  const SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImNxcXFrYmh6bWR4YXNndHlxYndnIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzkwNzA4MTAsImV4cCI6MjA5NDY0NjgxMH0.8I9rM-PMnSguKA48WSxIw7FKjWSkhzIBzjxdzPAC-xw".trim();
  function isSupabaseConfigured() {
    return SUPABASE_URL.length > 0 && SUPABASE_ANON_KEY.length > 0;
  }
  const TORN_ITEM_RECEIVE_LOG_TYPE = 4103;
  const TORN_LOG_PERMISSION_ERROR_CODE = "torn_log_permission";
  const TORN_LOG_PERMISSION_MESSAGE = "Your Torn API key needs Item receive logs. Log out, then reconnect with a new key from Create API Key.";
  class TornLogPermissionError extends Error {
    constructor(message = TORN_LOG_PERMISSION_MESSAGE) {
      super(message);
      __publicField(this, "code", TORN_LOG_PERMISSION_ERROR_CODE);
      this.name = "TornLogPermissionError";
    }
  }
  function isTornLogPermissionError(error2) {
    return error2 instanceof TornLogPermissionError || typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === TORN_LOG_PERMISSION_ERROR_CODE;
  }
  function isTornLogPermissionMessage(message) {
    return /logs \(item receive\)|item receive logs|log 61/i.test(message);
  }
  function isPermissionMessage$3(apiCode, message) {
    return apiCode === 16 || apiCode === 28 || /\b(access|permission|scope|selection|log)\b/i.test(message);
  }
  async function assertTornUserItemReceiveLogAccess(apiKey, fetchImpl = fetch) {
    const trimmedKey = apiKey.trim();
    if (!trimmedKey) {
      throw new Error("Torn API key is missing.");
    }
    const url = new URL("https://api.torn.com/user/");
    url.searchParams.set("selections", "log");
    url.searchParams.set("log", String(TORN_ITEM_RECEIVE_LOG_TYPE));
    url.searchParams.set("to", String(Math.floor(Date.now() / 1e3)));
    url.searchParams.set("key", trimmedKey);
    const response = await fetchImpl(url.href, { method: "GET" });
    const raw = await response.text();
    let payload;
    try {
      payload = typeof raw === "string" && raw.length > 0 ? JSON.parse(raw) : {};
    } catch {
      throw new Error(
        `Torn user logs returned invalid JSON (HTTP ${response.status}).`
      );
    }
    const apiError = payload.error;
    if (!response.ok || apiError) {
      const apiCode = typeof (apiError == null ? void 0 : apiError.code) === "number" ? apiError.code : void 0;
      const apiMessage = typeof (apiError == null ? void 0 : apiError.error) === "string" ? apiError.error : `HTTP ${response.status}`;
      if (isPermissionMessage$3(apiCode, apiMessage)) {
        throw new TornLogPermissionError();
      }
      throw new Error(`Torn user logs failed: ${apiMessage}`);
    }
  }
  const SESSION_KEY = "torn_session";
  const API_KEY_KEY = "torn_api_key";
  async function assertMarketSession(session) {
    const customFetch = activeAuthFetch;
    const client2 = supabaseJs.createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
      global: {
        fetch: customFetch,
        headers: {
          Authorization: `Bearer ${session.access_token}`
        }
      },
      auth: {
        persistSession: false,
        autoRefreshToken: false,
        detectSessionInUrl: false
      }
    });
    const { data, error: error2 } = await client2.rpc("get_my_profile").maybeSingle();
    if (error2) {
      const msg = error2.message ?? "unknown error";
      const jwtKeyTypeHint = /wrong key type|no suitable key|key_ops/i.test(msg) ? " Your Supabase project verifies ES256 JWTs (JWT Signing Keys). Set JWT_SIGNING_JWK on verify_torn_key to a private ES256 key imported in Dashboard -> Settings -> JWT Keys, then rotate keys. Legacy JWT_SECRET (HS256) alone will not work on this project." : " If using legacy HS256, JWT_SECRET must match Project Settings -> API -> JWT Secret. If using JWT Signing Keys (ES256), set JWT_SIGNING_JWK instead.";
      throw new Error(`Marketplace session rejected (${msg}).${jwtKeyTypeHint}`);
    }
    if (!data) {
      throw new Error(
        "Marketplace session is invalid (no profile for this token). Check JWT_SECRET on edge functions matches your Supabase project."
      );
    }
  }
  let activeAuthFetch;
  function createAuthService(storage, customFetch) {
    activeAuthFetch = customFetch;
    async function getStoredSession() {
      const session = await storage.get(SESSION_KEY);
      if (!session) return null;
      if (session.expires_at * 1e3 <= Date.now()) {
        await storage.remove(SESSION_KEY);
        return null;
      }
      return session;
    }
    async function getStoredApiKey() {
      const key = await storage.get(API_KEY_KEY);
      return typeof key === "string" && key.length > 0 ? key : null;
    }
    async function clearAuth() {
      await storage.remove([SESSION_KEY, API_KEY_KEY]);
    }
    async function verifyAndStoreSession(apiKey) {
      if (!isSupabaseConfigured()) {
        throw new Error(
          "Supabase is not configured. Set VITE_SUPABASE_URL and VITE_SUPABASE_ANON_KEY."
        );
      }
      const endpoint = `${SUPABASE_URL}/functions/v1/verify_torn_key`;
      let res;
      try {
        res = await (customFetch ?? fetch)(endpoint, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${SUPABASE_ANON_KEY}`,
            apikey: SUPABASE_ANON_KEY
          },
          body: JSON.stringify({ api_key: apiKey })
        });
      } catch (err) {
        const hint2 = err instanceof Error ? err.message : "Network request failed";
        throw new Error(
          `Could not reach Supabase (${hint2}). Check VITE_SUPABASE_URL is the project root, e.g. https://YOUR_REF.supabase.co`
        );
      }
      const raw = await res.text();
      let data;
      try {
        data = JSON.parse(raw);
      } catch {
        throw new Error(
          `Auth failed (${res.status}): invalid response from server. Is verify_torn_key deployed?`
        );
      }
      if (!res.ok || data.error) {
        const message = data.error ?? `Auth failed (HTTP ${res.status})`;
        if (isTornLogPermissionMessage(message)) {
          throw new TornLogPermissionError();
        }
        throw new Error(message);
      }
      if (!data.access_token || !data.torn_xid) {
        throw new Error(
          "Auth response missing session fields. Check JWT_SECRET on edge functions."
        );
      }
      const session = {
        access_token: data.access_token,
        expires_at: data.expires_at,
        torn_xid: data.torn_xid,
        display_name: data.display_name
      };
      await assertMarketSession(session);
      await storage.setMany({
        [SESSION_KEY]: session,
        [API_KEY_KEY]: apiKey
      });
      return session;
    }
    async function refreshSessionIfNeeded() {
      const session = await getStoredSession();
      if (session) {
        try {
          await assertMarketSession(session);
          return session;
        } catch {
          await clearAuth();
        }
      }
      const apiKey = await getStoredApiKey();
      if (!apiKey) return null;
      try {
        return await verifyAndStoreSession(apiKey);
      } catch {
        await clearAuth();
        return null;
      }
    }
    return {
      clearAuth,
      getStoredApiKey,
      getStoredSession,
      refreshSessionIfNeeded,
      verifyAndStoreSession
    };
  }
  const STORAGE_PREFIX = "tp:";
  const LEGACY_STORAGE_PREFIX = "tlm:";
  const CONTENT_HOST_ID = "the-panel-root";
  const LEGACY_CONTENT_HOST_ID = "torn-losses-market-root";
  function namespacedKey(prefix, key) {
    return `${prefix}${key}`;
  }
  function currentNamespacedKey(key) {
    return namespacedKey(STORAGE_PREFIX, key);
  }
  function legacyNamespacedKey(key) {
    return namespacedKey(LEGACY_STORAGE_PREFIX, key);
  }
  function readLocalStorageWithMigration(storage, key) {
    const currentKey = currentNamespacedKey(key);
    const current = storage.getItem(currentKey);
    if (current != null) return current;
    const legacyKey = legacyNamespacedKey(key);
    const legacy = storage.getItem(legacyKey);
    if (legacy == null) return null;
    try {
      storage.setItem(currentKey, legacy);
      storage.removeItem(legacyKey);
    } catch {
    }
    return legacy;
  }
  function writeLocalStorageCurrent(storage, key, value) {
    storage.setItem(currentNamespacedKey(key), value);
  }
  function removeLocalStorageCurrent(storage, key) {
    storage.removeItem(currentNamespacedKey(key));
    storage.removeItem(legacyNamespacedKey(key));
  }
  function getGmApi() {
    return typeof GM === "undefined" ? null : GM;
  }
  function readLocalFallback(key) {
    const raw = readLocalStorageWithMigration(window.localStorage, key);
    if (raw == null) return null;
    try {
      return JSON.parse(raw);
    } catch {
      return null;
    }
  }
  function writeLocalFallback(key, value) {
    writeLocalStorageCurrent(
      window.localStorage,
      key,
      JSON.stringify(value)
    );
  }
  function removeLocalFallback(key) {
    removeLocalStorageCurrent(window.localStorage, key);
  }
  async function migrateGmValue(key) {
    var _a2;
    const gm = getGmApi();
    if (!(gm == null ? void 0 : gm.getValue) || !gm.setValue) return null;
    const currentKey = currentNamespacedKey(key);
    const current = await gm.getValue(currentKey, null);
    if (current != null) return current;
    const legacyKey = legacyNamespacedKey(key);
    const legacy = await gm.getValue(legacyKey, null);
    if (legacy == null) return null;
    await gm.setValue(currentKey, legacy);
    await ((_a2 = gm.deleteValue) == null ? void 0 : _a2.call(gm, legacyKey));
    return legacy;
  }
  async function getValue(key) {
    const gm = getGmApi();
    if (gm == null ? void 0 : gm.getValue) {
      return migrateGmValue(key);
    }
    return readLocalFallback(key);
  }
  async function setValue(key, value) {
    const gm = getGmApi();
    if (gm == null ? void 0 : gm.setValue) {
      await gm.setValue(currentNamespacedKey(key), value);
      if (gm.deleteValue) {
        await gm.deleteValue(legacyNamespacedKey(key));
      }
      return;
    }
    writeLocalFallback(key, value);
  }
  const userscriptStorage = {
    get: getValue,
    async getMany(keys) {
      const result = {};
      for (const key of Array.isArray(keys) ? keys : [keys]) {
        const value = await getValue(key);
        if (value !== null) result[key] = value;
      }
      return result;
    },
    set: setValue,
    async setMany(items) {
      await Promise.all(
        Object.entries(items).map(([key, value]) => setValue(key, value))
      );
    },
    async remove(keys) {
      const gm = getGmApi();
      await Promise.all(
        (Array.isArray(keys) ? keys : [keys]).map(async (key) => {
          if (gm == null ? void 0 : gm.deleteValue) {
            await gm.deleteValue(currentNamespacedKey(key));
            await gm.deleteValue(legacyNamespacedKey(key));
            return;
          }
          removeLocalFallback(key);
        })
      );
    }
  };
  function verifyAlarmName(kind, id2) {
    return `contract-verify-${kind}-${id2}`;
  }
  const PENDING_LOSS_KEY = "pending_verify_loss";
  const PENDING_REDEEM_KEY = "pending_verify_redeem";
  const PENDING_BOUNTY_KEY = "pending_verify_bounty";
  function pendingStorageKey(kind) {
    return kind === "loss" ? PENDING_LOSS_KEY : kind === "redeem" ? PENDING_REDEEM_KEY : PENDING_BOUNTY_KEY;
  }
  const TORN_UNAVAILABLE_HINT = "Torn is temporarily unavailable — turn in again when the API is back.";
  class TornVerifySuspendedError extends Error {
    constructor(message, tornOutage, tornVerifySuspended) {
      super(message);
      __publicField(this, "tornOutage");
      __publicField(this, "tornVerifySuspended");
      this.name = "TornVerifySuspendedError";
      this.tornOutage = tornOutage;
      this.tornVerifySuspended = tornVerifySuspended;
    }
  }
  function isPollSuspendedResponse(status2, data) {
    return status2 === 503 && (data.torn_outage === true || data.torn_verify_suspended === true);
  }
  function formatPollVerifyError(status2, data) {
    const base = data.error ?? `Verification failed (HTTP ${status2})`;
    if (isPollSuspendedResponse(status2, data)) {
      return `${base} ${TORN_UNAVAILABLE_HINT}`;
    }
    return base;
  }
  function throwIfPollVerifyFailed(status2, data) {
    if (status2 >= 200 && status2 < 300 && !data.error) return;
    const message = formatPollVerifyError(status2, data);
    if (isPollSuspendedResponse(status2, data)) {
      throw new TornVerifySuspendedError(
        message,
        data.torn_outage === true,
        data.torn_verify_suspended === true
      );
    }
    throw new Error(message);
  }
  async function invokeVerifyFulfillment(accessToken, kind, id2, apiKey, customFetch) {
    const functionName = kind === "loss" ? "poll_loss_contract" : kind === "redeem" ? "poll_redeem_fulfillment" : "poll_bounty_contract";
    const body2 = kind === "loss" ? { contract_id: id2, api_key: apiKey } : kind === "redeem" ? { fulfillment_id: id2, api_key: apiKey } : { contract_id: id2, api_key: apiKey };
    const requestFetch = customFetch ?? fetch;
    const res = await requestFetch(`${SUPABASE_URL}/functions/v1/${functionName}`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${accessToken}`,
        apikey: SUPABASE_ANON_KEY
      },
      body: JSON.stringify(body2)
    });
    const raw = await res.text();
    let data = {};
    try {
      data = JSON.parse(raw);
    } catch {
      throw new Error(
        `Verification failed (${res.status}): invalid response from server`
      );
    }
    throwIfPollVerifyFailed(res.status, data);
  }
  const timers = /* @__PURE__ */ new Map();
  function timerKey(kind, id2) {
    return verifyAlarmName(kind, id2);
  }
  function clearTimer(kind, id2) {
    const key = timerKey(kind, id2);
    const timer2 = timers.get(key);
    if (!timer2) return;
    window.clearTimeout(timer2);
    timers.delete(key);
  }
  function getPendingJob(storage, kind) {
    return storage.get(pendingStorageKey(kind));
  }
  async function runScheduledContractVerify(storage, auth2, scheduler2, job, fetchImpl) {
    const pending = await getPendingJob(storage, job.kind);
    if (!pending || pending.id !== job.id) return;
    const session = await auth2.getSession();
    const apiKey = await auth2.getApiKey();
    if (!session || !apiKey) {
      await scheduler2.clearContractVerify(job.kind, job.id);
      return;
    }
    try {
      await invokeVerifyFulfillment(
        session.access_token,
        job.kind,
        job.id,
        apiKey,
        fetchImpl
      );
      await scheduler2.clearContractVerify(job.kind, job.id);
    } catch (err) {
      console.warn("contract verify userscript timer failed", err);
      if (err instanceof TornVerifySuspendedError) {
        if (!pending.periodic) {
          await scheduler2.scheduleContractVerify({
            ...pending,
            endsAtMs: Date.now(),
            periodic: true
          });
        }
        return;
      }
      if (!pending.periodic) {
        await scheduler2.clearContractVerify(job.kind, job.id);
      }
    }
  }
  function scheduleTimer(storage, auth2, scheduler2, job, fetchImpl) {
    clearTimer(job.kind, job.id);
    const delay2 = job.periodic ? 6e4 : Math.max(job.endsAtMs - Date.now(), 1e3);
    const timer2 = window.setTimeout(() => {
      timers.delete(timerKey(job.kind, job.id));
      void runScheduledContractVerify(storage, auth2, scheduler2, job, fetchImpl).finally(() => {
        if (job.periodic) {
          void getPendingJob(storage, job.kind).then((pending) => {
            if ((pending == null ? void 0 : pending.id) === job.id && pending.periodic) {
              scheduleTimer(storage, auth2, scheduler2, pending, fetchImpl);
            }
          });
        }
      });
    }, delay2);
    timers.set(timerKey(job.kind, job.id), timer2);
  }
  function createUserscriptScheduler(storage, auth2, fetchImpl = fetch) {
    const scheduler2 = {
      async scheduleContractVerify(job) {
        const existing = await getPendingJob(storage, job.kind);
        if (existing && existing.id !== job.id) {
          clearTimer(existing.kind, existing.id);
        }
        await storage.set(pendingStorageKey(job.kind), job);
        scheduleTimer(storage, auth2, scheduler2, job, fetchImpl);
      },
      async clearContractVerify(kind, id2) {
        const pending = await getPendingJob(storage, kind);
        const targetId = id2 ?? (pending == null ? void 0 : pending.id);
        if (targetId) clearTimer(kind, targetId);
        await storage.remove(pendingStorageKey(kind));
      },
      async resumePendingJobs() {
        for (const kind of ["loss", "redeem", "bounty"]) {
          const pending = await getPendingJob(storage, kind);
          if (pending == null ? void 0 : pending.id) {
            scheduleTimer(storage, auth2, scheduler2, pending, fetchImpl);
          }
        }
      }
    };
    return scheduler2;
  }
  function headersToRecord(headers) {
    if (!headers) return {};
    return Object.fromEntries(new Headers(headers).entries());
  }
  function parseResponseHeaders(rawHeaders) {
    const headers = new Headers();
    for (const line of rawHeaders.split(/\r?\n/)) {
      const separator = line.indexOf(":");
      if (separator <= 0) continue;
      headers.append(
        line.slice(0, separator).trim(),
        line.slice(separator + 1).trim()
      );
    }
    return headers;
  }
  function requestUrl(input2) {
    if (input2 instanceof Request) return input2.url;
    if (input2 instanceof URL) return input2.href;
    return String(input2);
  }
  const userscriptFetch = async (input2, init = {}) => {
    const gm = globalThis.GM;
    if (!(gm == null ? void 0 : gm.xmlHttpRequest)) {
      return fetch(input2, init);
    }
    const request = input2 instanceof Request ? input2 : null;
    const method = init.method ?? (request == null ? void 0 : request.method) ?? "GET";
    const headers = headersToRecord(init.headers ?? (request == null ? void 0 : request.headers));
    const body2 = init.body ?? null;
    return new Promise((resolve, reject) => {
      var _a2, _b;
      let aborted = false;
      const requestHandle = (_a2 = gm.xmlHttpRequest) == null ? void 0 : _a2.call(gm, {
        method,
        url: requestUrl(input2),
        headers,
        data: body2,
        onload: (response) => {
          if (aborted) return;
          resolve(
            new Response(response.responseText, {
              status: response.status,
              statusText: response.statusText,
              headers: parseResponseHeaders(response.responseHeaders)
            })
          );
        },
        onerror: (error2) => {
          if (!aborted) reject(error2);
        },
        ontimeout: (error2) => {
          if (!aborted) reject(error2);
        },
        onabort: () => {
          aborted = true;
          reject(new DOMException("The operation was aborted.", "AbortError"));
        }
      });
      (_b = init.signal) == null ? void 0 : _b.addEventListener(
        "abort",
        () => {
          var _a3;
          aborted = true;
          (_a3 = requestHandle == null ? void 0 : requestHandle.abort) == null ? void 0 : _a3.call(requestHandle);
          reject(new DOMException("The operation was aborted.", "AbortError"));
        },
        { once: true }
      );
    });
  };
  const XANAX_ITEM_ID$1 = 206;
  const SCRIPT_DOLLARS_PER_XANAX = 1e6;
  const TORN_MARKET_PERMISSION_ERROR_CODE = "torn_market_permission";
  class TornMarketPermissionError extends Error {
    constructor(message) {
      super(message);
      __publicField(this, "code", TORN_MARKET_PERMISSION_ERROR_CODE);
      this.name = "TornMarketPermissionError";
    }
  }
  class TornMarketApiError extends Error {
    constructor(message, apiCode = null) {
      super(message);
      __publicField(this, "apiCode");
      this.name = "TornMarketApiError";
      this.apiCode = apiCode;
    }
  }
  function isTornMarketPermissionError(error2) {
    return error2 instanceof TornMarketPermissionError || typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === TORN_MARKET_PERMISSION_ERROR_CODE;
  }
  function isPermissionMessage$2(apiCode, message) {
    if (apiCode === 23) return false;
    return apiCode === 16 || /\b(access|permission|scope|selection|market|itemmarket)\b/i.test(message);
  }
  function readJsonObject(raw) {
    return typeof raw === "object" && raw !== null ? raw : {};
  }
  function extractAveragePrice(payload) {
    var _a2;
    const itemmarket = payload.itemmarket;
    if (!itemmarket) return null;
    if (!Array.isArray(itemmarket)) {
      const averagePrice = (_a2 = itemmarket.item) == null ? void 0 : _a2.average_price;
      if (typeof averagePrice === "number" && Number.isFinite(averagePrice)) {
        return Math.round(averagePrice);
      }
      const listings = itemmarket.listings;
      if (Array.isArray(listings) && listings.length > 0) {
        const costs2 = listings.map((row2) => row2.cost ?? row2.price).filter((value) => typeof value === "number" && Number.isFinite(value));
        if (costs2.length > 0) {
          return Math.round(costs2.reduce((sum, value) => sum + value, 0) / costs2.length);
        }
      }
      return null;
    }
    const costs = itemmarket.map((row2) => row2.cost ?? row2.price).filter((value) => typeof value === "number" && Number.isFinite(value));
    if (costs.length === 0) return null;
    return Math.round(costs.reduce((sum, value) => sum + value, 0) / costs.length);
  }
  function buildXanaxMarketPrice(payload, averagePrice) {
    const itemmarket = payload.itemmarket;
    const item = itemmarket && !Array.isArray(itemmarket) ? itemmarket.item : void 0;
    const cacheSource = itemmarket && !Array.isArray(itemmarket) ? itemmarket : void 0;
    return {
      itemId: typeof (item == null ? void 0 : item.id) === "number" ? item.id : XANAX_ITEM_ID$1,
      itemName: typeof (item == null ? void 0 : item.name) === "string" ? item.name : "Xanax",
      averagePrice,
      cacheTimestamp: typeof (cacheSource == null ? void 0 : cacheSource.cache_timestamp) === "number" ? cacheSource.cache_timestamp : null,
      cacheDelay: typeof (cacheSource == null ? void 0 : cacheSource.cache_delay) === "number" ? cacheSource.cache_delay : null,
      fetchedAt: Date.now()
    };
  }
  async function requestItemmarket(url, apiVariant, fetchImpl) {
    const response = await fetchImpl(url, { method: "GET" });
    const raw = await response.text();
    let payload;
    try {
      payload = readJsonObject(JSON.parse(raw));
    } catch {
      throw new TornMarketApiError(
        `Torn itemmarket (${apiVariant}) returned invalid JSON (HTTP ${response.status}).`
      );
    }
    const apiError = payload.error;
    if (!response.ok || apiError) {
      const apiCode = typeof (apiError == null ? void 0 : apiError.code) === "number" ? apiError.code : void 0;
      const apiMessage = typeof (apiError == null ? void 0 : apiError.error) === "string" ? apiError.error : `HTTP ${response.status}`;
      if (isPermissionMessage$2(apiCode, apiMessage)) {
        throw new TornMarketPermissionError(
          "Your Torn API key needs item market access. Log out, then reconnect with a new key from Create API Key."
        );
      }
      throw new TornMarketApiError(
        `Torn itemmarket (${apiVariant}) failed: ${apiMessage}`,
        apiCode ?? null
      );
    }
    const averagePrice = extractAveragePrice(payload);
    if (averagePrice === null) {
      throw new TornMarketApiError(
        `Torn itemmarket (${apiVariant}) response is missing average_price.`
      );
    }
    return buildXanaxMarketPrice(payload, averagePrice);
  }
  async function fetchXanaxMarketPriceV1(apiKey, fetchImpl) {
    const url = new URL(`https://api.torn.com/market/${XANAX_ITEM_ID$1}`);
    url.searchParams.set("selections", "itemmarket");
    url.searchParams.set("key", apiKey);
    return requestItemmarket(url.href, "v1", fetchImpl);
  }
  async function fetchXanaxMarketPriceV2(apiKey, fetchImpl) {
    const url = new URL(
      `https://api.torn.com/v2/market/${XANAX_ITEM_ID$1}/itemmarket`
    );
    url.searchParams.set("limit", "1");
    url.searchParams.set("offset", "0");
    url.searchParams.set("key", apiKey);
    return requestItemmarket(url.href, "v2", fetchImpl);
  }
  async function fetchXanaxMarketPrice$1(apiKey, fetchImpl = fetch) {
    const trimmedKey = apiKey.trim();
    if (!trimmedKey) {
      throw new TornMarketApiError("Torn API key is missing.");
    }
    let v1Error;
    try {
      return await fetchXanaxMarketPriceV1(trimmedKey, fetchImpl);
    } catch (err) {
      v1Error = err;
    }
    try {
      return await fetchXanaxMarketPriceV2(trimmedKey, fetchImpl);
    } catch (v2Err) {
      if (isTornMarketPermissionError(v2Err) && isTornMarketPermissionError(v1Error)) {
        throw v1Error;
      }
      throw v2Err;
    }
  }
  const PEPPER_SPRAY_ITEM_ID = 392;
  const PILLOW_ITEM_ID = 440;
  const TORN_EQUIPMENT_PERMISSION_ERROR_CODE = "torn_equipment_permission";
  const TORN_EQUIPMENT_PERMISSION_MESSAGE = "Your Torn API key needs the equipment selection enabled. Log out, then reconnect with a new key from Create API Key.";
  class TornEquipmentPermissionError extends Error {
    constructor(message = TORN_EQUIPMENT_PERMISSION_MESSAGE) {
      super(message);
      __publicField(this, "code", TORN_EQUIPMENT_PERMISSION_ERROR_CODE);
      this.name = "TornEquipmentPermissionError";
    }
  }
  class TornEquipmentError extends Error {
    constructor(message) {
      super(message);
      this.name = "TornEquipmentError";
    }
  }
  function isTornEquipmentPermissionError(error2) {
    return error2 instanceof TornEquipmentPermissionError || typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === TORN_EQUIPMENT_PERMISSION_ERROR_CODE;
  }
  function isPermissionMessage$1(apiCode, message) {
    return apiCode === 16 || apiCode === 28 || /\b(access|permission|scope|selection|equipment)\b/i.test(message);
  }
  function equipmentEntries(payload) {
    const raw = payload.equipment;
    if (!raw) return [];
    if (Array.isArray(raw)) return raw;
    return Object.values(raw);
  }
  function isItemEquipped(items, itemId) {
    return items.some((entry) => {
      const id2 = Number(entry.ID ?? entry.id);
      const equipped = Number(entry.equipped ?? 0);
      return id2 === itemId && equipped > 0;
    });
  }
  async function fetchTornUserEquipment(apiKey, fetchImpl = fetch) {
    const trimmedKey = apiKey.trim();
    if (!trimmedKey) {
      throw new Error("Torn API key is missing.");
    }
    const url = new URL("https://api.torn.com/user/");
    url.searchParams.set("selections", "equipment");
    url.searchParams.set("key", trimmedKey);
    const response = await fetchImpl(url.href, { method: "GET" });
    const raw = await response.text();
    let payload;
    try {
      payload = typeof raw === "string" && raw.length > 0 ? JSON.parse(raw) : {};
    } catch {
      throw new Error(
        `Torn user equipment returned invalid JSON (HTTP ${response.status}).`
      );
    }
    const apiError = payload.error;
    if (!response.ok || apiError) {
      const apiCode = typeof (apiError == null ? void 0 : apiError.code) === "number" ? apiError.code : void 0;
      const apiMessage = typeof (apiError == null ? void 0 : apiError.error) === "string" ? apiError.error : `HTTP ${response.status}`;
      if (isPermissionMessage$1(apiCode, apiMessage)) {
        throw new TornEquipmentPermissionError();
      }
      throw new Error(`Torn user equipment failed: ${apiMessage}`);
    }
    return equipmentEntries(payload);
  }
  const EQUIPMENT_REQUIRED = {
    escapes: { itemId: PEPPER_SPRAY_ITEM_ID, label: "Pepper Spray" },
    stalemates: { itemId: PILLOW_ITEM_ID, label: "Pillow" }
  };
  function assertContractEquipmentFromItems(contractType, items) {
    const requirement = EQUIPMENT_REQUIRED[contractType];
    if (isItemEquipped(items, requirement.itemId)) return;
    throw new TornEquipmentError(
      `Equip ${requirement.label} before posting a ${contractType} contract.`
    );
  }
  const CONTRACT_FULFILL_MINUTES = 10;
  const CONTRACT_COUNTDOWN_SECONDS = 9 * 60 + 59;
  const CONTRACT_LOSS_MIN = 1;
  const CONTRACT_LOSS_MAX = 10;
  const CURRENT_USER_XID = 4183306;
  const BUYER_ORDER_QTY_MIN = 1;
  const BUYER_ORDER_QTY_MAX = 1e4;
  const ALERT_WITHDRAWAL_QTY_MIN = 1;
  const ALERT_WITHDRAWAL_QTY_MAX = BUYER_ORDER_QTY_MAX;
  const BUYER_ORDER_PRICE_MIN = 1e5;
  const BUYER_ORDER_PRICE_MAX = 1e10;
  const INSURANCE_COVERAGE_MIN = 1e5;
  const INSURANCE_COVERAGE_MAX = 1e7;
  const INSURANCE_XANAX_OD_HOURS = 2;
  const INSURANCE_ECSTASY_OD_HOURS = 2;
  const INSURANCE_LONG_TERM_XAN_HOURS = 24;
  const TIMELY_LOSS_TORN_PAY_MIN = 25e4;
  const RECOMMENDED_ESCAPE_STALEMATE_TORN_PAY_MIN = 5e5;
  const DEPOSIT_PLAYER_XID = 2297468;
  const DEPOSIT_PLAYER_NAME = "ARCANE";
  const DEPOSIT_ITEM_NAME = "Xanax";
  const DEPOSIT_ITEM_URL = "https://www.torn.com/item.php";
  function getTornAttackUrl(targetUserId) {
    return `https://www.torn.com/page.php?sid=attack&user2ID=${targetUserId}`;
  }
  const DEPOSIT_AMOUNT_PER_ITEM = 1e6;
  const WITHDRAW_MILLION = 1e6;
  const REDEEMING_REQUESTER_PLACEHOLDER_ID = 1111111;
  const REDEEMING_PAY_PERCENT = 5;
  const REDEEMING_FULFILL_MINUTES = 2;
  const REDEEMING_COUNTDOWN_SECONDS = 2 * 60 - 1;
  const DEFAULT_USER_BALANCE = 0;
  const RECOMMENDED_PRODUCTIVITY_PRICE_TORN = 35e6;
  const PRODUCTIVITY_BOOST_COUNTDOWN_SECONDS = 2 * 60 - 1;
  const RECOMMENDED_EMBARGO_PRICE_TORN = 5e6;
  const RECOMMENDED_FLIGHT_DELAY_PRICE_TORN = 15e6;
  const FLIGHT_DELAY_COUNTDOWN_SECONDS = 2 * 60 - 1;
  const SIMPLE_SERVICE_COUNTDOWN_SECONDS = 2 * 60 - 1;
  const COMPANIES_SPECIAL_URL = "https://www.torn.com/companies.php?step=your&type=1";
  const BOUNTY_SERVICE_FEE_PTS = 15e4;
  const BOUNTY_QTY_MIN = 1;
  const BOUNTY_QTY_MAX = BUYER_ORDER_QTY_MAX;
  const BOUNTY_FULFILL_MAX = 10;
  const BOUNTY_COUNTDOWN_SECONDS = 2 * 60 - 1;
  const REFERRAL_REFEREE_BONUS = 5e4;
  const REFERRAL_REFERRER_BONUS = 1e5;
  const REFERRAL_LOSSES_THRESHOLD = 20;
  const REFERRAL_XANAX_THRESHOLD = 2;
  const REFERRAL_WINDOW_HOURS = 24;
  const TAKE_CONTRACT_BUTTON_LABEL = "Take Contract";
  const INSURANCE_PLANS = [
    {
      id: "xanax_od",
      label: "Xanax OD",
      subtitle: "Covers Xanax overdose for the next 2 hours",
      durationHours: INSURANCE_XANAX_OD_HOURS,
      payoutMultiplier: 30,
      supportsAutoRenew: false
    },
    {
      id: "ecstasy_od",
      label: "Ecstasy OD",
      subtitle: "Covers Ecstasy overdose for the next 2 hours",
      durationHours: INSURANCE_ECSTASY_OD_HOURS,
      payoutMultiplier: 20,
      supportsAutoRenew: false
    },
    {
      id: "long_term_xan",
      label: "Xanax OD (24h+)",
      subtitle: "Covers Xanax overdoses indefinitely",
      durationHours: INSURANCE_LONG_TERM_XAN_HOURS,
      payoutMultiplier: 10,
      supportsAutoRenew: true
    }
  ];
  const INSURANCE_PLAN_LABELS = {
    xanax_od: "Xanax OD",
    ecstasy_od: "Ecstasy OD",
    long_term_xan: "Xanax OD (24h+)"
  };
  const INSURANCE_PLAN_SHORT_LABELS = {
    xanax_od: "X",
    ecstasy_od: "E",
    long_term_xan: "X+"
  };
  const PLAN_BY_ID = Object.fromEntries(
    INSURANCE_PLANS.map((plan) => [plan.id, plan])
  );
  function getInsurancePlan(planId) {
    return PLAN_BY_ID[planId];
  }
  function formatInsuranceDuration(hours) {
    if (hours >= 24 && hours % 24 === 0) {
      const days2 = hours / 24;
      return days2 === 1 ? "24h" : `${days2}d`;
    }
    return `${hours}h`;
  }
  function formatInsuranceWithinWindow(hours) {
    if (hours === 2) return "within the next 2 hours";
    if (hours === 24) return "within the next 24 hours";
    return `within the next ${hours} hours`;
  }
  function formatInsuranceInWindow(hours) {
    if (hours === 2) return "within the next 2 hours";
    if (hours === 24) return "within the next 24 hours";
    return `within the next ${hours} hours`;
  }
  function formatInsuranceMultiplier(multiplier) {
    return `${multiplier}× your payment`;
  }
  const OD_RISK_REDUCTION_PERK_REGEX = /\+\s*(\d+(?:\.\d+)?)\s*%\s*drug overdose risk reduction/i;
  const PERK_ARRAY_KEYS = [
    "faction_perks",
    "job_perks",
    "property_perks",
    "education_perks",
    "enhancer_perks",
    "book_perks",
    "stock_perks",
    "merit_perks",
    "company_perks"
  ];
  function parseOdRiskReductionPercents(perksResponse) {
    const percents = [];
    for (const key of PERK_ARRAY_KEYS) {
      const arr = perksResponse[key];
      if (!Array.isArray(arr)) continue;
      for (const entry of arr) {
        if (typeof entry !== "string") continue;
        const match = entry.match(OD_RISK_REDUCTION_PERK_REGEX);
        if (match) {
          const pct = Number(match[1]);
          if (Number.isFinite(pct) && pct > 0 && pct < 100) {
            percents.push(pct);
          }
        }
      }
    }
    return percents;
  }
  function computePayoutFactorFromOdReductions(odReductionPercents) {
    if (odReductionPercents.length === 0) return 1;
    let odChanceRemaining = 1;
    for (const pct of odReductionPercents) {
      odChanceRemaining *= 1 - pct / 100;
    }
    if (odChanceRemaining <= 0 || odChanceRemaining >= 1) return 1;
    return 1 / odChanceRemaining;
  }
  function computeEffectiveMultiplier(basePlanMultiplier, odReductionPercents) {
    const factor = computePayoutFactorFromOdReductions(odReductionPercents);
    return Math.floor(basePlanMultiplier * factor);
  }
  function computeEffectiveMultipliers(odReductionPercents) {
    const result = {};
    for (const plan of INSURANCE_PLANS) {
      result[plan.id] = computeEffectiveMultiplier(
        plan.payoutMultiplier,
        odReductionPercents
      );
    }
    return result;
  }
  function computeInsurancePayout(premium, effectiveMultiplier) {
    return premium * effectiveMultiplier;
  }
  const TORN_PERKS_PERMISSION_ERROR_CODE = "torn_perks_permission";
  const TORN_PERKS_PERMISSION_MESSAGE = "Your Torn API key needs the perks selection enabled. Log out, then reconnect with a new key from Create API Key.";
  class TornPerksPermissionError extends Error {
    constructor(message = TORN_PERKS_PERMISSION_MESSAGE) {
      super(message);
      __publicField(this, "code", TORN_PERKS_PERMISSION_ERROR_CODE);
      this.name = "TornPerksPermissionError";
    }
  }
  function isTornPerksPermissionError(error2) {
    return error2 instanceof TornPerksPermissionError || typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === TORN_PERKS_PERMISSION_ERROR_CODE;
  }
  function isPermissionMessage(apiCode, message) {
    return apiCode === 16 || apiCode === 28 || /\b(access|permission|scope|selection|perks)\b/i.test(message);
  }
  async function fetchTornUserPerks(apiKey, fetchImpl = fetch) {
    const trimmedKey = apiKey.trim();
    if (!trimmedKey) {
      throw new Error("Torn API key is missing.");
    }
    const url = new URL("https://api.torn.com/user/");
    url.searchParams.set("selections", "perks");
    url.searchParams.set("key", trimmedKey);
    const response = await fetchImpl(url.href, { method: "GET" });
    const raw = await response.text();
    let payload;
    try {
      payload = typeof raw === "string" && raw.length > 0 ? JSON.parse(raw) : {};
    } catch {
      throw new Error(
        `Torn user perks returned invalid JSON (HTTP ${response.status}).`
      );
    }
    const apiError = payload.error;
    if (!response.ok || apiError) {
      const apiCode = typeof (apiError == null ? void 0 : apiError.code) === "number" ? apiError.code : void 0;
      const apiMessage = typeof (apiError == null ? void 0 : apiError.error) === "string" ? apiError.error : `HTTP ${response.status}`;
      if (isPermissionMessage(apiCode, apiMessage)) {
        throw new TornPerksPermissionError();
      }
      throw new Error(`Torn user perks failed: ${apiMessage}`);
    }
    return payload;
  }
  const authService = createAuthService(userscriptStorage, userscriptFetch);
  const auth = {
    getApiKey: authService.getStoredApiKey,
    getSession: authService.refreshSessionIfNeeded,
    setApiKey: (apiKey) => authService.verifyAndStoreSession(apiKey),
    signOut: authService.clearAuth
  };
  const scheduler$1 = createUserscriptScheduler(userscriptStorage, auth, userscriptFetch);
  async function fetchXanaxMarketPrice() {
    const apiKey = await auth.getApiKey();
    if (!apiKey) {
      throw new Error("Connect your Torn API key before loading Xanax market price.");
    }
    return fetchXanaxMarketPrice$1(apiKey, userscriptFetch);
  }
  async function assertItemReceiveLogAccess() {
    const apiKey = await auth.getApiKey();
    if (!apiKey) {
      throw new Error("Connect your Torn API key before checking log access.");
    }
    await assertTornUserItemReceiveLogAccess(apiKey, userscriptFetch);
  }
  async function fetchUserEquipment() {
    const apiKey = await auth.getApiKey();
    if (!apiKey) {
      throw new Error("Connect your Torn API key before checking equipment.");
    }
    return fetchTornUserEquipment(apiKey, userscriptFetch);
  }
  async function fetchUserPerks() {
    const apiKey = await auth.getApiKey();
    if (!apiKey) {
      throw new Error("Connect your Torn API key before loading perks.");
    }
    return fetchTornUserPerks(apiKey, userscriptFetch);
  }
  void scheduler$1.resumePendingJobs();
  const userscriptRuntime = {
    name: "userscript",
    fetch: userscriptFetch,
    storage: userscriptStorage,
    auth,
    scheduler: scheduler$1,
    tornMarket: {
      fetchXanaxMarketPrice,
      assertItemReceiveLogAccess,
      fetchUserEquipment,
      fetchUserPerks
    },
    ui: {
      onToggleSidebar(handler) {
        var _a2;
        const gm = typeof GM === "undefined" ? null : GM;
        const commandId = (_a2 = gm == null ? void 0 : gm.registerMenuCommand) == null ? void 0 : _a2.call(
          gm,
          `Toggle ${BRAND_NAME} sidebar`,
          handler
        );
        return () => {
          var _a3;
          if (commandId != null) {
            (_a3 = gm == null ? void 0 : gm.unregisterMenuCommand) == null ? void 0 : _a3.call(gm, commandId);
          }
        };
      }
    }
  };
  var jsxRuntime = { exports: {} };
  var reactJsxRuntime_production_min = {};
  var react = { exports: {} };
  var react_production_min = {};
  /**
   * @license React
   * react.production.min.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   */
  var hasRequiredReact_production_min;
  function requireReact_production_min() {
    if (hasRequiredReact_production_min) return react_production_min;
    hasRequiredReact_production_min = 1;
    var l = Symbol.for("react.element"), n = Symbol.for("react.portal"), p = Symbol.for("react.fragment"), q = Symbol.for("react.strict_mode"), r = Symbol.for("react.profiler"), t = Symbol.for("react.provider"), u = Symbol.for("react.context"), v = Symbol.for("react.forward_ref"), w = Symbol.for("react.suspense"), x = Symbol.for("react.memo"), y = Symbol.for("react.lazy"), z = Symbol.iterator;
    function A(a) {
      if (null === a || "object" !== typeof a) return null;
      a = z && a[z] || a["@@iterator"];
      return "function" === typeof a ? a : null;
    }
    var B = { isMounted: function() {
      return false;
    }, enqueueForceUpdate: function() {
    }, enqueueReplaceState: function() {
    }, enqueueSetState: function() {
    } }, C = Object.assign, D = {};
    function E(a, b, e) {
      this.props = a;
      this.context = b;
      this.refs = D;
      this.updater = e || B;
    }
    E.prototype.isReactComponent = {};
    E.prototype.setState = function(a, b) {
      if ("object" !== typeof a && "function" !== typeof a && null != a) throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");
      this.updater.enqueueSetState(this, a, b, "setState");
    };
    E.prototype.forceUpdate = function(a) {
      this.updater.enqueueForceUpdate(this, a, "forceUpdate");
    };
    function F() {
    }
    F.prototype = E.prototype;
    function G(a, b, e) {
      this.props = a;
      this.context = b;
      this.refs = D;
      this.updater = e || B;
    }
    var H = G.prototype = new F();
    H.constructor = G;
    C(H, E.prototype);
    H.isPureReactComponent = true;
    var I = Array.isArray, J = Object.prototype.hasOwnProperty, K = { current: null }, L = { key: true, ref: true, __self: true, __source: true };
    function M(a, b, e) {
      var d, c = {}, k = null, h = null;
      if (null != b) for (d in void 0 !== b.ref && (h = b.ref), void 0 !== b.key && (k = "" + b.key), b) J.call(b, d) && !L.hasOwnProperty(d) && (c[d] = b[d]);
      var g = arguments.length - 2;
      if (1 === g) c.children = e;
      else if (1 < g) {
        for (var f = Array(g), m = 0; m < g; m++) f[m] = arguments[m + 2];
        c.children = f;
      }
      if (a && a.defaultProps) for (d in g = a.defaultProps, g) void 0 === c[d] && (c[d] = g[d]);
      return { $$typeof: l, type: a, key: k, ref: h, props: c, _owner: K.current };
    }
    function N(a, b) {
      return { $$typeof: l, type: a.type, key: b, ref: a.ref, props: a.props, _owner: a._owner };
    }
    function O(a) {
      return "object" === typeof a && null !== a && a.$$typeof === l;
    }
    function escape(a) {
      var b = { "=": "=0", ":": "=2" };
      return "$" + a.replace(/[=:]/g, function(a2) {
        return b[a2];
      });
    }
    var P = /\/+/g;
    function Q(a, b) {
      return "object" === typeof a && null !== a && null != a.key ? escape("" + a.key) : b.toString(36);
    }
    function R(a, b, e, d, c) {
      var k = typeof a;
      if ("undefined" === k || "boolean" === k) a = null;
      var h = false;
      if (null === a) h = true;
      else switch (k) {
        case "string":
        case "number":
          h = true;
          break;
        case "object":
          switch (a.$$typeof) {
            case l:
            case n:
              h = true;
          }
      }
      if (h) return h = a, c = c(h), a = "" === d ? "." + Q(h, 0) : d, I(c) ? (e = "", null != a && (e = a.replace(P, "$&/") + "/"), R(c, b, e, "", function(a2) {
        return a2;
      })) : null != c && (O(c) && (c = N(c, e + (!c.key || h && h.key === c.key ? "" : ("" + c.key).replace(P, "$&/") + "/") + a)), b.push(c)), 1;
      h = 0;
      d = "" === d ? "." : d + ":";
      if (I(a)) for (var g = 0; g < a.length; g++) {
        k = a[g];
        var f = d + Q(k, g);
        h += R(k, b, e, f, c);
      }
      else if (f = A(a), "function" === typeof f) for (a = f.call(a), g = 0; !(k = a.next()).done; ) k = k.value, f = d + Q(k, g++), h += R(k, b, e, f, c);
      else if ("object" === k) throw b = String(a), Error("Objects are not valid as a React child (found: " + ("[object Object]" === b ? "object with keys {" + Object.keys(a).join(", ") + "}" : b) + "). If you meant to render a collection of children, use an array instead.");
      return h;
    }
    function S(a, b, e) {
      if (null == a) return a;
      var d = [], c = 0;
      R(a, d, "", "", function(a2) {
        return b.call(e, a2, c++);
      });
      return d;
    }
    function T(a) {
      if (-1 === a._status) {
        var b = a._result;
        b = b();
        b.then(function(b2) {
          if (0 === a._status || -1 === a._status) a._status = 1, a._result = b2;
        }, function(b2) {
          if (0 === a._status || -1 === a._status) a._status = 2, a._result = b2;
        });
        -1 === a._status && (a._status = 0, a._result = b);
      }
      if (1 === a._status) return a._result.default;
      throw a._result;
    }
    var U = { current: null }, V = { transition: null }, W = { ReactCurrentDispatcher: U, ReactCurrentBatchConfig: V, ReactCurrentOwner: K };
    function X() {
      throw Error("act(...) is not supported in production builds of React.");
    }
    react_production_min.Children = { map: S, forEach: function(a, b, e) {
      S(a, function() {
        b.apply(this, arguments);
      }, e);
    }, count: function(a) {
      var b = 0;
      S(a, function() {
        b++;
      });
      return b;
    }, toArray: function(a) {
      return S(a, function(a2) {
        return a2;
      }) || [];
    }, only: function(a) {
      if (!O(a)) throw Error("React.Children.only expected to receive a single React element child.");
      return a;
    } };
    react_production_min.Component = E;
    react_production_min.Fragment = p;
    react_production_min.Profiler = r;
    react_production_min.PureComponent = G;
    react_production_min.StrictMode = q;
    react_production_min.Suspense = w;
    react_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = W;
    react_production_min.act = X;
    react_production_min.cloneElement = function(a, b, e) {
      if (null === a || void 0 === a) throw Error("React.cloneElement(...): The argument must be a React element, but you passed " + a + ".");
      var d = C({}, a.props), c = a.key, k = a.ref, h = a._owner;
      if (null != b) {
        void 0 !== b.ref && (k = b.ref, h = K.current);
        void 0 !== b.key && (c = "" + b.key);
        if (a.type && a.type.defaultProps) var g = a.type.defaultProps;
        for (f in b) J.call(b, f) && !L.hasOwnProperty(f) && (d[f] = void 0 === b[f] && void 0 !== g ? g[f] : b[f]);
      }
      var f = arguments.length - 2;
      if (1 === f) d.children = e;
      else if (1 < f) {
        g = Array(f);
        for (var m = 0; m < f; m++) g[m] = arguments[m + 2];
        d.children = g;
      }
      return { $$typeof: l, type: a.type, key: c, ref: k, props: d, _owner: h };
    };
    react_production_min.createContext = function(a) {
      a = { $$typeof: u, _currentValue: a, _currentValue2: a, _threadCount: 0, Provider: null, Consumer: null, _defaultValue: null, _globalName: null };
      a.Provider = { $$typeof: t, _context: a };
      return a.Consumer = a;
    };
    react_production_min.createElement = M;
    react_production_min.createFactory = function(a) {
      var b = M.bind(null, a);
      b.type = a;
      return b;
    };
    react_production_min.createRef = function() {
      return { current: null };
    };
    react_production_min.forwardRef = function(a) {
      return { $$typeof: v, render: a };
    };
    react_production_min.isValidElement = O;
    react_production_min.lazy = function(a) {
      return { $$typeof: y, _payload: { _status: -1, _result: a }, _init: T };
    };
    react_production_min.memo = function(a, b) {
      return { $$typeof: x, type: a, compare: void 0 === b ? null : b };
    };
    react_production_min.startTransition = function(a) {
      var b = V.transition;
      V.transition = {};
      try {
        a();
      } finally {
        V.transition = b;
      }
    };
    react_production_min.unstable_act = X;
    react_production_min.useCallback = function(a, b) {
      return U.current.useCallback(a, b);
    };
    react_production_min.useContext = function(a) {
      return U.current.useContext(a);
    };
    react_production_min.useDebugValue = function() {
    };
    react_production_min.useDeferredValue = function(a) {
      return U.current.useDeferredValue(a);
    };
    react_production_min.useEffect = function(a, b) {
      return U.current.useEffect(a, b);
    };
    react_production_min.useId = function() {
      return U.current.useId();
    };
    react_production_min.useImperativeHandle = function(a, b, e) {
      return U.current.useImperativeHandle(a, b, e);
    };
    react_production_min.useInsertionEffect = function(a, b) {
      return U.current.useInsertionEffect(a, b);
    };
    react_production_min.useLayoutEffect = function(a, b) {
      return U.current.useLayoutEffect(a, b);
    };
    react_production_min.useMemo = function(a, b) {
      return U.current.useMemo(a, b);
    };
    react_production_min.useReducer = function(a, b, e) {
      return U.current.useReducer(a, b, e);
    };
    react_production_min.useRef = function(a) {
      return U.current.useRef(a);
    };
    react_production_min.useState = function(a) {
      return U.current.useState(a);
    };
    react_production_min.useSyncExternalStore = function(a, b, e) {
      return U.current.useSyncExternalStore(a, b, e);
    };
    react_production_min.useTransition = function() {
      return U.current.useTransition();
    };
    react_production_min.version = "18.3.1";
    return react_production_min;
  }
  var hasRequiredReact;
  function requireReact() {
    if (hasRequiredReact) return react.exports;
    hasRequiredReact = 1;
    {
      react.exports = requireReact_production_min();
    }
    return react.exports;
  }
  /**
   * @license React
   * react-jsx-runtime.production.min.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   */
  var hasRequiredReactJsxRuntime_production_min;
  function requireReactJsxRuntime_production_min() {
    if (hasRequiredReactJsxRuntime_production_min) return reactJsxRuntime_production_min;
    hasRequiredReactJsxRuntime_production_min = 1;
    var f = requireReact(), k = Symbol.for("react.element"), l = Symbol.for("react.fragment"), m = Object.prototype.hasOwnProperty, n = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, p = { key: true, ref: true, __self: true, __source: true };
    function q(c, a, g) {
      var b, d = {}, e = null, h = null;
      void 0 !== g && (e = "" + g);
      void 0 !== a.key && (e = "" + a.key);
      void 0 !== a.ref && (h = a.ref);
      for (b in a) m.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]);
      if (c && c.defaultProps) for (b in a = c.defaultProps, a) void 0 === d[b] && (d[b] = a[b]);
      return { $$typeof: k, type: c, key: e, ref: h, props: d, _owner: n.current };
    }
    reactJsxRuntime_production_min.Fragment = l;
    reactJsxRuntime_production_min.jsx = q;
    reactJsxRuntime_production_min.jsxs = q;
    return reactJsxRuntime_production_min;
  }
  var hasRequiredJsxRuntime;
  function requireJsxRuntime() {
    if (hasRequiredJsxRuntime) return jsxRuntime.exports;
    hasRequiredJsxRuntime = 1;
    {
      jsxRuntime.exports = requireReactJsxRuntime_production_min();
    }
    return jsxRuntime.exports;
  }
  var jsxRuntimeExports = requireJsxRuntime();
  var client$1 = {};
  var reactDom = { exports: {} };
  var reactDom_production_min = {};
  var scheduler = { exports: {} };
  var scheduler_production_min = {};
  /**
   * @license React
   * scheduler.production.min.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   */
  var hasRequiredScheduler_production_min;
  function requireScheduler_production_min() {
    if (hasRequiredScheduler_production_min) return scheduler_production_min;
    hasRequiredScheduler_production_min = 1;
    (function(exports) {
      function f(a, b) {
        var c = a.length;
        a.push(b);
        a: for (; 0 < c; ) {
          var d = c - 1 >>> 1, e = a[d];
          if (0 < g(e, b)) a[d] = b, a[c] = e, c = d;
          else break a;
        }
      }
      function h(a) {
        return 0 === a.length ? null : a[0];
      }
      function k(a) {
        if (0 === a.length) return null;
        var b = a[0], c = a.pop();
        if (c !== b) {
          a[0] = c;
          a: for (var d = 0, e = a.length, w = e >>> 1; d < w; ) {
            var m = 2 * (d + 1) - 1, C = a[m], n = m + 1, x = a[n];
            if (0 > g(C, c)) n < e && 0 > g(x, C) ? (a[d] = x, a[n] = c, d = n) : (a[d] = C, a[m] = c, d = m);
            else if (n < e && 0 > g(x, c)) a[d] = x, a[n] = c, d = n;
            else break a;
          }
        }
        return b;
      }
      function g(a, b) {
        var c = a.sortIndex - b.sortIndex;
        return 0 !== c ? c : a.id - b.id;
      }
      if ("object" === typeof performance && "function" === typeof performance.now) {
        var l = performance;
        exports.unstable_now = function() {
          return l.now();
        };
      } else {
        var p = Date, q = p.now();
        exports.unstable_now = function() {
          return p.now() - q;
        };
      }
      var r = [], t = [], u = 1, v = null, y = 3, z = false, A = false, B = false, D = "function" === typeof setTimeout ? setTimeout : null, E = "function" === typeof clearTimeout ? clearTimeout : null, F = "undefined" !== typeof setImmediate ? setImmediate : null;
      "undefined" !== typeof navigator && void 0 !== navigator.scheduling && void 0 !== navigator.scheduling.isInputPending && navigator.scheduling.isInputPending.bind(navigator.scheduling);
      function G(a) {
        for (var b = h(t); null !== b; ) {
          if (null === b.callback) k(t);
          else if (b.startTime <= a) k(t), b.sortIndex = b.expirationTime, f(r, b);
          else break;
          b = h(t);
        }
      }
      function H(a) {
        B = false;
        G(a);
        if (!A) if (null !== h(r)) A = true, I(J);
        else {
          var b = h(t);
          null !== b && K(H, b.startTime - a);
        }
      }
      function J(a, b) {
        A = false;
        B && (B = false, E(L), L = -1);
        z = true;
        var c = y;
        try {
          G(b);
          for (v = h(r); null !== v && (!(v.expirationTime > b) || a && !M()); ) {
            var d = v.callback;
            if ("function" === typeof d) {
              v.callback = null;
              y = v.priorityLevel;
              var e = d(v.expirationTime <= b);
              b = exports.unstable_now();
              "function" === typeof e ? v.callback = e : v === h(r) && k(r);
              G(b);
            } else k(r);
            v = h(r);
          }
          if (null !== v) var w = true;
          else {
            var m = h(t);
            null !== m && K(H, m.startTime - b);
            w = false;
          }
          return w;
        } finally {
          v = null, y = c, z = false;
        }
      }
      var N = false, O = null, L = -1, P = 5, Q = -1;
      function M() {
        return exports.unstable_now() - Q < P ? false : true;
      }
      function R() {
        if (null !== O) {
          var a = exports.unstable_now();
          Q = a;
          var b = true;
          try {
            b = O(true, a);
          } finally {
            b ? S() : (N = false, O = null);
          }
        } else N = false;
      }
      var S;
      if ("function" === typeof F) S = function() {
        F(R);
      };
      else if ("undefined" !== typeof MessageChannel) {
        var T = new MessageChannel(), U = T.port2;
        T.port1.onmessage = R;
        S = function() {
          U.postMessage(null);
        };
      } else S = function() {
        D(R, 0);
      };
      function I(a) {
        O = a;
        N || (N = true, S());
      }
      function K(a, b) {
        L = D(function() {
          a(exports.unstable_now());
        }, b);
      }
      exports.unstable_IdlePriority = 5;
      exports.unstable_ImmediatePriority = 1;
      exports.unstable_LowPriority = 4;
      exports.unstable_NormalPriority = 3;
      exports.unstable_Profiling = null;
      exports.unstable_UserBlockingPriority = 2;
      exports.unstable_cancelCallback = function(a) {
        a.callback = null;
      };
      exports.unstable_continueExecution = function() {
        A || z || (A = true, I(J));
      };
      exports.unstable_forceFrameRate = function(a) {
        0 > a || 125 < a ? console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported") : P = 0 < a ? Math.floor(1e3 / a) : 5;
      };
      exports.unstable_getCurrentPriorityLevel = function() {
        return y;
      };
      exports.unstable_getFirstCallbackNode = function() {
        return h(r);
      };
      exports.unstable_next = function(a) {
        switch (y) {
          case 1:
          case 2:
          case 3:
            var b = 3;
            break;
          default:
            b = y;
        }
        var c = y;
        y = b;
        try {
          return a();
        } finally {
          y = c;
        }
      };
      exports.unstable_pauseExecution = function() {
      };
      exports.unstable_requestPaint = function() {
      };
      exports.unstable_runWithPriority = function(a, b) {
        switch (a) {
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
            break;
          default:
            a = 3;
        }
        var c = y;
        y = a;
        try {
          return b();
        } finally {
          y = c;
        }
      };
      exports.unstable_scheduleCallback = function(a, b, c) {
        var d = exports.unstable_now();
        "object" === typeof c && null !== c ? (c = c.delay, c = "number" === typeof c && 0 < c ? d + c : d) : c = d;
        switch (a) {
          case 1:
            var e = -1;
            break;
          case 2:
            e = 250;
            break;
          case 5:
            e = 1073741823;
            break;
          case 4:
            e = 1e4;
            break;
          default:
            e = 5e3;
        }
        e = c + e;
        a = { id: u++, callback: b, priorityLevel: a, startTime: c, expirationTime: e, sortIndex: -1 };
        c > d ? (a.sortIndex = c, f(t, a), null === h(r) && a === h(t) && (B ? (E(L), L = -1) : B = true, K(H, c - d))) : (a.sortIndex = e, f(r, a), A || z || (A = true, I(J)));
        return a;
      };
      exports.unstable_shouldYield = M;
      exports.unstable_wrapCallback = function(a) {
        var b = y;
        return function() {
          var c = y;
          y = b;
          try {
            return a.apply(this, arguments);
          } finally {
            y = c;
          }
        };
      };
    })(scheduler_production_min);
    return scheduler_production_min;
  }
  var hasRequiredScheduler;
  function requireScheduler() {
    if (hasRequiredScheduler) return scheduler.exports;
    hasRequiredScheduler = 1;
    {
      scheduler.exports = requireScheduler_production_min();
    }
    return scheduler.exports;
  }
  /**
   * @license React
   * react-dom.production.min.js
   *
   * Copyright (c) Facebook, Inc. and its affiliates.
   *
   * This source code is licensed under the MIT license found in the
   * LICENSE file in the root directory of this source tree.
   */
  var hasRequiredReactDom_production_min;
  function requireReactDom_production_min() {
    if (hasRequiredReactDom_production_min) return reactDom_production_min;
    hasRequiredReactDom_production_min = 1;
    var aa = requireReact(), ca = requireScheduler();
    function p(a) {
      for (var b = "https://reactjs.org/docs/error-decoder.html?invariant=" + a, c = 1; c < arguments.length; c++) b += "&args[]=" + encodeURIComponent(arguments[c]);
      return "Minified React error #" + a + "; visit " + b + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings.";
    }
    var da = /* @__PURE__ */ new Set(), ea = {};
    function fa(a, b) {
      ha(a, b);
      ha(a + "Capture", b);
    }
    function ha(a, b) {
      ea[a] = b;
      for (a = 0; a < b.length; a++) da.add(b[a]);
    }
    var ia = !("undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement), ja = Object.prototype.hasOwnProperty, ka = /^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/, la = {}, ma = {};
    function oa(a) {
      if (ja.call(ma, a)) return true;
      if (ja.call(la, a)) return false;
      if (ka.test(a)) return ma[a] = true;
      la[a] = true;
      return false;
    }
    function pa(a, b, c, d) {
      if (null !== c && 0 === c.type) return false;
      switch (typeof b) {
        case "function":
        case "symbol":
          return true;
        case "boolean":
          if (d) return false;
          if (null !== c) return !c.acceptsBooleans;
          a = a.toLowerCase().slice(0, 5);
          return "data-" !== a && "aria-" !== a;
        default:
          return false;
      }
    }
    function qa(a, b, c, d) {
      if (null === b || "undefined" === typeof b || pa(a, b, c, d)) return true;
      if (d) return false;
      if (null !== c) switch (c.type) {
        case 3:
          return !b;
        case 4:
          return false === b;
        case 5:
          return isNaN(b);
        case 6:
          return isNaN(b) || 1 > b;
      }
      return false;
    }
    function v(a, b, c, d, e, f, g) {
      this.acceptsBooleans = 2 === b || 3 === b || 4 === b;
      this.attributeName = d;
      this.attributeNamespace = e;
      this.mustUseProperty = c;
      this.propertyName = a;
      this.type = b;
      this.sanitizeURL = f;
      this.removeEmptyString = g;
    }
    var z = {};
    "children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a) {
      z[a] = new v(a, 0, false, a, null, false, false);
    });
    [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(a) {
      var b = a[0];
      z[b] = new v(b, 1, false, a[1], null, false, false);
    });
    ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(a) {
      z[a] = new v(a, 2, false, a.toLowerCase(), null, false, false);
    });
    ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(a) {
      z[a] = new v(a, 2, false, a, null, false, false);
    });
    "allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a) {
      z[a] = new v(a, 3, false, a.toLowerCase(), null, false, false);
    });
    ["checked", "multiple", "muted", "selected"].forEach(function(a) {
      z[a] = new v(a, 3, true, a, null, false, false);
    });
    ["capture", "download"].forEach(function(a) {
      z[a] = new v(a, 4, false, a, null, false, false);
    });
    ["cols", "rows", "size", "span"].forEach(function(a) {
      z[a] = new v(a, 6, false, a, null, false, false);
    });
    ["rowSpan", "start"].forEach(function(a) {
      z[a] = new v(a, 5, false, a.toLowerCase(), null, false, false);
    });
    var ra = /[\-:]([a-z])/g;
    function sa(a) {
      return a[1].toUpperCase();
    }
    "accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a) {
      var b = a.replace(
        ra,
        sa
      );
      z[b] = new v(b, 1, false, a, null, false, false);
    });
    "xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a) {
      var b = a.replace(ra, sa);
      z[b] = new v(b, 1, false, a, "http://www.w3.org/1999/xlink", false, false);
    });
    ["xml:base", "xml:lang", "xml:space"].forEach(function(a) {
      var b = a.replace(ra, sa);
      z[b] = new v(b, 1, false, a, "http://www.w3.org/XML/1998/namespace", false, false);
    });
    ["tabIndex", "crossOrigin"].forEach(function(a) {
      z[a] = new v(a, 1, false, a.toLowerCase(), null, false, false);
    });
    z.xlinkHref = new v("xlinkHref", 1, false, "xlink:href", "http://www.w3.org/1999/xlink", true, false);
    ["src", "href", "action", "formAction"].forEach(function(a) {
      z[a] = new v(a, 1, false, a.toLowerCase(), null, true, true);
    });
    function ta(a, b, c, d) {
      var e = z.hasOwnProperty(b) ? z[b] : null;
      if (null !== e ? 0 !== e.type : d || !(2 < b.length) || "o" !== b[0] && "O" !== b[0] || "n" !== b[1] && "N" !== b[1]) qa(b, c, e, d) && (c = null), d || null === e ? oa(b) && (null === c ? a.removeAttribute(b) : a.setAttribute(b, "" + c)) : e.mustUseProperty ? a[e.propertyName] = null === c ? 3 === e.type ? false : "" : c : (b = e.attributeName, d = e.attributeNamespace, null === c ? a.removeAttribute(b) : (e = e.type, c = 3 === e || 4 === e && true === c ? "" : "" + c, d ? a.setAttributeNS(d, b, c) : a.setAttribute(b, c)));
    }
    var ua = aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED, va = Symbol.for("react.element"), wa = Symbol.for("react.portal"), ya = Symbol.for("react.fragment"), za = Symbol.for("react.strict_mode"), Aa = Symbol.for("react.profiler"), Ba = Symbol.for("react.provider"), Ca = Symbol.for("react.context"), Da = Symbol.for("react.forward_ref"), Ea = Symbol.for("react.suspense"), Fa = Symbol.for("react.suspense_list"), Ga = Symbol.for("react.memo"), Ha = Symbol.for("react.lazy");
    var Ia = Symbol.for("react.offscreen");
    var Ja = Symbol.iterator;
    function Ka(a) {
      if (null === a || "object" !== typeof a) return null;
      a = Ja && a[Ja] || a["@@iterator"];
      return "function" === typeof a ? a : null;
    }
    var A = Object.assign, La;
    function Ma(a) {
      if (void 0 === La) try {
        throw Error();
      } catch (c) {
        var b = c.stack.trim().match(/\n( *(at )?)/);
        La = b && b[1] || "";
      }
      return "\n" + La + a;
    }
    var Na = false;
    function Oa(a, b) {
      if (!a || Na) return "";
      Na = true;
      var c = Error.prepareStackTrace;
      Error.prepareStackTrace = void 0;
      try {
        if (b) if (b = function() {
          throw Error();
        }, Object.defineProperty(b.prototype, "props", { set: function() {
          throw Error();
        } }), "object" === typeof Reflect && Reflect.construct) {
          try {
            Reflect.construct(b, []);
          } catch (l) {
            var d = l;
          }
          Reflect.construct(a, [], b);
        } else {
          try {
            b.call();
          } catch (l) {
            d = l;
          }
          a.call(b.prototype);
        }
        else {
          try {
            throw Error();
          } catch (l) {
            d = l;
          }
          a();
        }
      } catch (l) {
        if (l && d && "string" === typeof l.stack) {
          for (var e = l.stack.split("\n"), f = d.stack.split("\n"), g = e.length - 1, h = f.length - 1; 1 <= g && 0 <= h && e[g] !== f[h]; ) h--;
          for (; 1 <= g && 0 <= h; g--, h--) if (e[g] !== f[h]) {
            if (1 !== g || 1 !== h) {
              do
                if (g--, h--, 0 > h || e[g] !== f[h]) {
                  var k = "\n" + e[g].replace(" at new ", " at ");
                  a.displayName && k.includes("<anonymous>") && (k = k.replace("<anonymous>", a.displayName));
                  return k;
                }
              while (1 <= g && 0 <= h);
            }
            break;
          }
        }
      } finally {
        Na = false, Error.prepareStackTrace = c;
      }
      return (a = a ? a.displayName || a.name : "") ? Ma(a) : "";
    }
    function Pa(a) {
      switch (a.tag) {
        case 5:
          return Ma(a.type);
        case 16:
          return Ma("Lazy");
        case 13:
          return Ma("Suspense");
        case 19:
          return Ma("SuspenseList");
        case 0:
        case 2:
        case 15:
          return a = Oa(a.type, false), a;
        case 11:
          return a = Oa(a.type.render, false), a;
        case 1:
          return a = Oa(a.type, true), a;
        default:
          return "";
      }
    }
    function Qa(a) {
      if (null == a) return null;
      if ("function" === typeof a) return a.displayName || a.name || null;
      if ("string" === typeof a) return a;
      switch (a) {
        case ya:
          return "Fragment";
        case wa:
          return "Portal";
        case Aa:
          return "Profiler";
        case za:
          return "StrictMode";
        case Ea:
          return "Suspense";
        case Fa:
          return "SuspenseList";
      }
      if ("object" === typeof a) switch (a.$$typeof) {
        case Ca:
          return (a.displayName || "Context") + ".Consumer";
        case Ba:
          return (a._context.displayName || "Context") + ".Provider";
        case Da:
          var b = a.render;
          a = a.displayName;
          a || (a = b.displayName || b.name || "", a = "" !== a ? "ForwardRef(" + a + ")" : "ForwardRef");
          return a;
        case Ga:
          return b = a.displayName || null, null !== b ? b : Qa(a.type) || "Memo";
        case Ha:
          b = a._payload;
          a = a._init;
          try {
            return Qa(a(b));
          } catch (c) {
          }
      }
      return null;
    }
    function Ra(a) {
      var b = a.type;
      switch (a.tag) {
        case 24:
          return "Cache";
        case 9:
          return (b.displayName || "Context") + ".Consumer";
        case 10:
          return (b._context.displayName || "Context") + ".Provider";
        case 18:
          return "DehydratedFragment";
        case 11:
          return a = b.render, a = a.displayName || a.name || "", b.displayName || ("" !== a ? "ForwardRef(" + a + ")" : "ForwardRef");
        case 7:
          return "Fragment";
        case 5:
          return b;
        case 4:
          return "Portal";
        case 3:
          return "Root";
        case 6:
          return "Text";
        case 16:
          return Qa(b);
        case 8:
          return b === za ? "StrictMode" : "Mode";
        case 22:
          return "Offscreen";
        case 12:
          return "Profiler";
        case 21:
          return "Scope";
        case 13:
          return "Suspense";
        case 19:
          return "SuspenseList";
        case 25:
          return "TracingMarker";
        case 1:
        case 0:
        case 17:
        case 2:
        case 14:
        case 15:
          if ("function" === typeof b) return b.displayName || b.name || null;
          if ("string" === typeof b) return b;
      }
      return null;
    }
    function Sa(a) {
      switch (typeof a) {
        case "boolean":
        case "number":
        case "string":
        case "undefined":
          return a;
        case "object":
          return a;
        default:
          return "";
      }
    }
    function Ta(a) {
      var b = a.type;
      return (a = a.nodeName) && "input" === a.toLowerCase() && ("checkbox" === b || "radio" === b);
    }
    function Ua(a) {
      var b = Ta(a) ? "checked" : "value", c = Object.getOwnPropertyDescriptor(a.constructor.prototype, b), d = "" + a[b];
      if (!a.hasOwnProperty(b) && "undefined" !== typeof c && "function" === typeof c.get && "function" === typeof c.set) {
        var e = c.get, f = c.set;
        Object.defineProperty(a, b, { configurable: true, get: function() {
          return e.call(this);
        }, set: function(a2) {
          d = "" + a2;
          f.call(this, a2);
        } });
        Object.defineProperty(a, b, { enumerable: c.enumerable });
        return { getValue: function() {
          return d;
        }, setValue: function(a2) {
          d = "" + a2;
        }, stopTracking: function() {
          a._valueTracker = null;
          delete a[b];
        } };
      }
    }
    function Va(a) {
      a._valueTracker || (a._valueTracker = Ua(a));
    }
    function Wa(a) {
      if (!a) return false;
      var b = a._valueTracker;
      if (!b) return true;
      var c = b.getValue();
      var d = "";
      a && (d = Ta(a) ? a.checked ? "true" : "false" : a.value);
      a = d;
      return a !== c ? (b.setValue(a), true) : false;
    }
    function Xa(a) {
      a = a || ("undefined" !== typeof document ? document : void 0);
      if ("undefined" === typeof a) return null;
      try {
        return a.activeElement || a.body;
      } catch (b) {
        return a.body;
      }
    }
    function Ya(a, b) {
      var c = b.checked;
      return A({}, b, { defaultChecked: void 0, defaultValue: void 0, value: void 0, checked: null != c ? c : a._wrapperState.initialChecked });
    }
    function Za(a, b) {
      var c = null == b.defaultValue ? "" : b.defaultValue, d = null != b.checked ? b.checked : b.defaultChecked;
      c = Sa(null != b.value ? b.value : c);
      a._wrapperState = { initialChecked: d, initialValue: c, controlled: "checkbox" === b.type || "radio" === b.type ? null != b.checked : null != b.value };
    }
    function ab(a, b) {
      b = b.checked;
      null != b && ta(a, "checked", b, false);
    }
    function bb(a, b) {
      ab(a, b);
      var c = Sa(b.value), d = b.type;
      if (null != c) if ("number" === d) {
        if (0 === c && "" === a.value || a.value != c) a.value = "" + c;
      } else a.value !== "" + c && (a.value = "" + c);
      else if ("submit" === d || "reset" === d) {
        a.removeAttribute("value");
        return;
      }
      b.hasOwnProperty("value") ? cb(a, b.type, c) : b.hasOwnProperty("defaultValue") && cb(a, b.type, Sa(b.defaultValue));
      null == b.checked && null != b.defaultChecked && (a.defaultChecked = !!b.defaultChecked);
    }
    function db(a, b, c) {
      if (b.hasOwnProperty("value") || b.hasOwnProperty("defaultValue")) {
        var d = b.type;
        if (!("submit" !== d && "reset" !== d || void 0 !== b.value && null !== b.value)) return;
        b = "" + a._wrapperState.initialValue;
        c || b === a.value || (a.value = b);
        a.defaultValue = b;
      }
      c = a.name;
      "" !== c && (a.name = "");
      a.defaultChecked = !!a._wrapperState.initialChecked;
      "" !== c && (a.name = c);
    }
    function cb(a, b, c) {
      if ("number" !== b || Xa(a.ownerDocument) !== a) null == c ? a.defaultValue = "" + a._wrapperState.initialValue : a.defaultValue !== "" + c && (a.defaultValue = "" + c);
    }
    var eb = Array.isArray;
    function fb(a, b, c, d) {
      a = a.options;
      if (b) {
        b = {};
        for (var e = 0; e < c.length; e++) b["$" + c[e]] = true;
        for (c = 0; c < a.length; c++) e = b.hasOwnProperty("$" + a[c].value), a[c].selected !== e && (a[c].selected = e), e && d && (a[c].defaultSelected = true);
      } else {
        c = "" + Sa(c);
        b = null;
        for (e = 0; e < a.length; e++) {
          if (a[e].value === c) {
            a[e].selected = true;
            d && (a[e].defaultSelected = true);
            return;
          }
          null !== b || a[e].disabled || (b = a[e]);
        }
        null !== b && (b.selected = true);
      }
    }
    function gb(a, b) {
      if (null != b.dangerouslySetInnerHTML) throw Error(p(91));
      return A({}, b, { value: void 0, defaultValue: void 0, children: "" + a._wrapperState.initialValue });
    }
    function hb(a, b) {
      var c = b.value;
      if (null == c) {
        c = b.children;
        b = b.defaultValue;
        if (null != c) {
          if (null != b) throw Error(p(92));
          if (eb(c)) {
            if (1 < c.length) throw Error(p(93));
            c = c[0];
          }
          b = c;
        }
        null == b && (b = "");
        c = b;
      }
      a._wrapperState = { initialValue: Sa(c) };
    }
    function ib(a, b) {
      var c = Sa(b.value), d = Sa(b.defaultValue);
      null != c && (c = "" + c, c !== a.value && (a.value = c), null == b.defaultValue && a.defaultValue !== c && (a.defaultValue = c));
      null != d && (a.defaultValue = "" + d);
    }
    function jb(a) {
      var b = a.textContent;
      b === a._wrapperState.initialValue && "" !== b && null !== b && (a.value = b);
    }
    function kb(a) {
      switch (a) {
        case "svg":
          return "http://www.w3.org/2000/svg";
        case "math":
          return "http://www.w3.org/1998/Math/MathML";
        default:
          return "http://www.w3.org/1999/xhtml";
      }
    }
    function lb(a, b) {
      return null == a || "http://www.w3.org/1999/xhtml" === a ? kb(b) : "http://www.w3.org/2000/svg" === a && "foreignObject" === b ? "http://www.w3.org/1999/xhtml" : a;
    }
    var mb, nb = (function(a) {
      return "undefined" !== typeof MSApp && MSApp.execUnsafeLocalFunction ? function(b, c, d, e) {
        MSApp.execUnsafeLocalFunction(function() {
          return a(b, c, d, e);
        });
      } : a;
    })(function(a, b) {
      if ("http://www.w3.org/2000/svg" !== a.namespaceURI || "innerHTML" in a) a.innerHTML = b;
      else {
        mb = mb || document.createElement("div");
        mb.innerHTML = "<svg>" + b.valueOf().toString() + "</svg>";
        for (b = mb.firstChild; a.firstChild; ) a.removeChild(a.firstChild);
        for (; b.firstChild; ) a.appendChild(b.firstChild);
      }
    });
    function ob(a, b) {
      if (b) {
        var c = a.firstChild;
        if (c && c === a.lastChild && 3 === c.nodeType) {
          c.nodeValue = b;
          return;
        }
      }
      a.textContent = b;
    }
    var pb = {
      animationIterationCount: true,
      aspectRatio: true,
      borderImageOutset: true,
      borderImageSlice: true,
      borderImageWidth: true,
      boxFlex: true,
      boxFlexGroup: true,
      boxOrdinalGroup: true,
      columnCount: true,
      columns: true,
      flex: true,
      flexGrow: true,
      flexPositive: true,
      flexShrink: true,
      flexNegative: true,
      flexOrder: true,
      gridArea: true,
      gridRow: true,
      gridRowEnd: true,
      gridRowSpan: true,
      gridRowStart: true,
      gridColumn: true,
      gridColumnEnd: true,
      gridColumnSpan: true,
      gridColumnStart: true,
      fontWeight: true,
      lineClamp: true,
      lineHeight: true,
      opacity: true,
      order: true,
      orphans: true,
      tabSize: true,
      widows: true,
      zIndex: true,
      zoom: true,
      fillOpacity: true,
      floodOpacity: true,
      stopOpacity: true,
      strokeDasharray: true,
      strokeDashoffset: true,
      strokeMiterlimit: true,
      strokeOpacity: true,
      strokeWidth: true
    }, qb = ["Webkit", "ms", "Moz", "O"];
    Object.keys(pb).forEach(function(a) {
      qb.forEach(function(b) {
        b = b + a.charAt(0).toUpperCase() + a.substring(1);
        pb[b] = pb[a];
      });
    });
    function rb(a, b, c) {
      return null == b || "boolean" === typeof b || "" === b ? "" : c || "number" !== typeof b || 0 === b || pb.hasOwnProperty(a) && pb[a] ? ("" + b).trim() : b + "px";
    }
    function sb(a, b) {
      a = a.style;
      for (var c in b) if (b.hasOwnProperty(c)) {
        var d = 0 === c.indexOf("--"), e = rb(c, b[c], d);
        "float" === c && (c = "cssFloat");
        d ? a.setProperty(c, e) : a[c] = e;
      }
    }
    var tb = A({ menuitem: true }, { area: true, base: true, br: true, col: true, embed: true, hr: true, img: true, input: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true });
    function ub(a, b) {
      if (b) {
        if (tb[a] && (null != b.children || null != b.dangerouslySetInnerHTML)) throw Error(p(137, a));
        if (null != b.dangerouslySetInnerHTML) {
          if (null != b.children) throw Error(p(60));
          if ("object" !== typeof b.dangerouslySetInnerHTML || !("__html" in b.dangerouslySetInnerHTML)) throw Error(p(61));
        }
        if (null != b.style && "object" !== typeof b.style) throw Error(p(62));
      }
    }
    function vb(a, b) {
      if (-1 === a.indexOf("-")) return "string" === typeof b.is;
      switch (a) {
        case "annotation-xml":
        case "color-profile":
        case "font-face":
        case "font-face-src":
        case "font-face-uri":
        case "font-face-format":
        case "font-face-name":
        case "missing-glyph":
          return false;
        default:
          return true;
      }
    }
    var wb = null;
    function xb(a) {
      a = a.target || a.srcElement || window;
      a.correspondingUseElement && (a = a.correspondingUseElement);
      return 3 === a.nodeType ? a.parentNode : a;
    }
    var yb = null, zb = null, Ab = null;
    function Bb(a) {
      if (a = Cb(a)) {
        if ("function" !== typeof yb) throw Error(p(280));
        var b = a.stateNode;
        b && (b = Db(b), yb(a.stateNode, a.type, b));
      }
    }
    function Eb(a) {
      zb ? Ab ? Ab.push(a) : Ab = [a] : zb = a;
    }
    function Fb() {
      if (zb) {
        var a = zb, b = Ab;
        Ab = zb = null;
        Bb(a);
        if (b) for (a = 0; a < b.length; a++) Bb(b[a]);
      }
    }
    function Gb(a, b) {
      return a(b);
    }
    function Hb() {
    }
    var Ib = false;
    function Jb(a, b, c) {
      if (Ib) return a(b, c);
      Ib = true;
      try {
        return Gb(a, b, c);
      } finally {
        if (Ib = false, null !== zb || null !== Ab) Hb(), Fb();
      }
    }
    function Kb(a, b) {
      var c = a.stateNode;
      if (null === c) return null;
      var d = Db(c);
      if (null === d) return null;
      c = d[b];
      a: switch (b) {
        case "onClick":
        case "onClickCapture":
        case "onDoubleClick":
        case "onDoubleClickCapture":
        case "onMouseDown":
        case "onMouseDownCapture":
        case "onMouseMove":
        case "onMouseMoveCapture":
        case "onMouseUp":
        case "onMouseUpCapture":
        case "onMouseEnter":
          (d = !d.disabled) || (a = a.type, d = !("button" === a || "input" === a || "select" === a || "textarea" === a));
          a = !d;
          break a;
        default:
          a = false;
      }
      if (a) return null;
      if (c && "function" !== typeof c) throw Error(p(231, b, typeof c));
      return c;
    }
    var Lb = false;
    if (ia) try {
      var Mb = {};
      Object.defineProperty(Mb, "passive", { get: function() {
        Lb = true;
      } });
      window.addEventListener("test", Mb, Mb);
      window.removeEventListener("test", Mb, Mb);
    } catch (a) {
      Lb = false;
    }
    function Nb(a, b, c, d, e, f, g, h, k) {
      var l = Array.prototype.slice.call(arguments, 3);
      try {
        b.apply(c, l);
      } catch (m) {
        this.onError(m);
      }
    }
    var Ob = false, Pb = null, Qb = false, Rb = null, Sb = { onError: function(a) {
      Ob = true;
      Pb = a;
    } };
    function Tb(a, b, c, d, e, f, g, h, k) {
      Ob = false;
      Pb = null;
      Nb.apply(Sb, arguments);
    }
    function Ub(a, b, c, d, e, f, g, h, k) {
      Tb.apply(this, arguments);
      if (Ob) {
        if (Ob) {
          var l = Pb;
          Ob = false;
          Pb = null;
        } else throw Error(p(198));
        Qb || (Qb = true, Rb = l);
      }
    }
    function Vb(a) {
      var b = a, c = a;
      if (a.alternate) for (; b.return; ) b = b.return;
      else {
        a = b;
        do
          b = a, 0 !== (b.flags & 4098) && (c = b.return), a = b.return;
        while (a);
      }
      return 3 === b.tag ? c : null;
    }
    function Wb(a) {
      if (13 === a.tag) {
        var b = a.memoizedState;
        null === b && (a = a.alternate, null !== a && (b = a.memoizedState));
        if (null !== b) return b.dehydrated;
      }
      return null;
    }
    function Xb(a) {
      if (Vb(a) !== a) throw Error(p(188));
    }
    function Yb(a) {
      var b = a.alternate;
      if (!b) {
        b = Vb(a);
        if (null === b) throw Error(p(188));
        return b !== a ? null : a;
      }
      for (var c = a, d = b; ; ) {
        var e = c.return;
        if (null === e) break;
        var f = e.alternate;
        if (null === f) {
          d = e.return;
          if (null !== d) {
            c = d;
            continue;
          }
          break;
        }
        if (e.child === f.child) {
          for (f = e.child; f; ) {
            if (f === c) return Xb(e), a;
            if (f === d) return Xb(e), b;
            f = f.sibling;
          }
          throw Error(p(188));
        }
        if (c.return !== d.return) c = e, d = f;
        else {
          for (var g = false, h = e.child; h; ) {
            if (h === c) {
              g = true;
              c = e;
              d = f;
              break;
            }
            if (h === d) {
              g = true;
              d = e;
              c = f;
              break;
            }
            h = h.sibling;
          }
          if (!g) {
            for (h = f.child; h; ) {
              if (h === c) {
                g = true;
                c = f;
                d = e;
                break;
              }
              if (h === d) {
                g = true;
                d = f;
                c = e;
                break;
              }
              h = h.sibling;
            }
            if (!g) throw Error(p(189));
          }
        }
        if (c.alternate !== d) throw Error(p(190));
      }
      if (3 !== c.tag) throw Error(p(188));
      return c.stateNode.current === c ? a : b;
    }
    function Zb(a) {
      a = Yb(a);
      return null !== a ? $b(a) : null;
    }
    function $b(a) {
      if (5 === a.tag || 6 === a.tag) return a;
      for (a = a.child; null !== a; ) {
        var b = $b(a);
        if (null !== b) return b;
        a = a.sibling;
      }
      return null;
    }
    var ac = ca.unstable_scheduleCallback, bc = ca.unstable_cancelCallback, cc = ca.unstable_shouldYield, dc = ca.unstable_requestPaint, B = ca.unstable_now, ec = ca.unstable_getCurrentPriorityLevel, fc = ca.unstable_ImmediatePriority, gc = ca.unstable_UserBlockingPriority, hc = ca.unstable_NormalPriority, ic = ca.unstable_LowPriority, jc = ca.unstable_IdlePriority, kc = null, lc = null;
    function mc(a) {
      if (lc && "function" === typeof lc.onCommitFiberRoot) try {
        lc.onCommitFiberRoot(kc, a, void 0, 128 === (a.current.flags & 128));
      } catch (b) {
      }
    }
    var oc = Math.clz32 ? Math.clz32 : nc, pc = Math.log, qc = Math.LN2;
    function nc(a) {
      a >>>= 0;
      return 0 === a ? 32 : 31 - (pc(a) / qc | 0) | 0;
    }
    var rc = 64, sc = 4194304;
    function tc(a) {
      switch (a & -a) {
        case 1:
          return 1;
        case 2:
          return 2;
        case 4:
          return 4;
        case 8:
          return 8;
        case 16:
          return 16;
        case 32:
          return 32;
        case 64:
        case 128:
        case 256:
        case 512:
        case 1024:
        case 2048:
        case 4096:
        case 8192:
        case 16384:
        case 32768:
        case 65536:
        case 131072:
        case 262144:
        case 524288:
        case 1048576:
        case 2097152:
          return a & 4194240;
        case 4194304:
        case 8388608:
        case 16777216:
        case 33554432:
        case 67108864:
          return a & 130023424;
        case 134217728:
          return 134217728;
        case 268435456:
          return 268435456;
        case 536870912:
          return 536870912;
        case 1073741824:
          return 1073741824;
        default:
          return a;
      }
    }
    function uc(a, b) {
      var c = a.pendingLanes;
      if (0 === c) return 0;
      var d = 0, e = a.suspendedLanes, f = a.pingedLanes, g = c & 268435455;
      if (0 !== g) {
        var h = g & ~e;
        0 !== h ? d = tc(h) : (f &= g, 0 !== f && (d = tc(f)));
      } else g = c & ~e, 0 !== g ? d = tc(g) : 0 !== f && (d = tc(f));
      if (0 === d) return 0;
      if (0 !== b && b !== d && 0 === (b & e) && (e = d & -d, f = b & -b, e >= f || 16 === e && 0 !== (f & 4194240))) return b;
      0 !== (d & 4) && (d |= c & 16);
      b = a.entangledLanes;
      if (0 !== b) for (a = a.entanglements, b &= d; 0 < b; ) c = 31 - oc(b), e = 1 << c, d |= a[c], b &= ~e;
      return d;
    }
    function vc(a, b) {
      switch (a) {
        case 1:
        case 2:
        case 4:
          return b + 250;
        case 8:
        case 16:
        case 32:
        case 64:
        case 128:
        case 256:
        case 512:
        case 1024:
        case 2048:
        case 4096:
        case 8192:
        case 16384:
        case 32768:
        case 65536:
        case 131072:
        case 262144:
        case 524288:
        case 1048576:
        case 2097152:
          return b + 5e3;
        case 4194304:
        case 8388608:
        case 16777216:
        case 33554432:
        case 67108864:
          return -1;
        case 134217728:
        case 268435456:
        case 536870912:
        case 1073741824:
          return -1;
        default:
          return -1;
      }
    }
    function wc(a, b) {
      for (var c = a.suspendedLanes, d = a.pingedLanes, e = a.expirationTimes, f = a.pendingLanes; 0 < f; ) {
        var g = 31 - oc(f), h = 1 << g, k = e[g];
        if (-1 === k) {
          if (0 === (h & c) || 0 !== (h & d)) e[g] = vc(h, b);
        } else k <= b && (a.expiredLanes |= h);
        f &= ~h;
      }
    }
    function xc(a) {
      a = a.pendingLanes & -1073741825;
      return 0 !== a ? a : a & 1073741824 ? 1073741824 : 0;
    }
    function yc() {
      var a = rc;
      rc <<= 1;
      0 === (rc & 4194240) && (rc = 64);
      return a;
    }
    function zc(a) {
      for (var b = [], c = 0; 31 > c; c++) b.push(a);
      return b;
    }
    function Ac(a, b, c) {
      a.pendingLanes |= b;
      536870912 !== b && (a.suspendedLanes = 0, a.pingedLanes = 0);
      a = a.eventTimes;
      b = 31 - oc(b);
      a[b] = c;
    }
    function Bc(a, b) {
      var c = a.pendingLanes & ~b;
      a.pendingLanes = b;
      a.suspendedLanes = 0;
      a.pingedLanes = 0;
      a.expiredLanes &= b;
      a.mutableReadLanes &= b;
      a.entangledLanes &= b;
      b = a.entanglements;
      var d = a.eventTimes;
      for (a = a.expirationTimes; 0 < c; ) {
        var e = 31 - oc(c), f = 1 << e;
        b[e] = 0;
        d[e] = -1;
        a[e] = -1;
        c &= ~f;
      }
    }
    function Cc(a, b) {
      var c = a.entangledLanes |= b;
      for (a = a.entanglements; c; ) {
        var d = 31 - oc(c), e = 1 << d;
        e & b | a[d] & b && (a[d] |= b);
        c &= ~e;
      }
    }
    var C = 0;
    function Dc(a) {
      a &= -a;
      return 1 < a ? 4 < a ? 0 !== (a & 268435455) ? 16 : 536870912 : 4 : 1;
    }
    var Ec, Fc, Gc, Hc, Ic, Jc = false, Kc = [], Lc = null, Mc = null, Nc = null, Oc = /* @__PURE__ */ new Map(), Pc = /* @__PURE__ */ new Map(), Qc = [], Rc = "mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");
    function Sc(a, b) {
      switch (a) {
        case "focusin":
        case "focusout":
          Lc = null;
          break;
        case "dragenter":
        case "dragleave":
          Mc = null;
          break;
        case "mouseover":
        case "mouseout":
          Nc = null;
          break;
        case "pointerover":
        case "pointerout":
          Oc.delete(b.pointerId);
          break;
        case "gotpointercapture":
        case "lostpointercapture":
          Pc.delete(b.pointerId);
      }
    }
    function Tc(a, b, c, d, e, f) {
      if (null === a || a.nativeEvent !== f) return a = { blockedOn: b, domEventName: c, eventSystemFlags: d, nativeEvent: f, targetContainers: [e] }, null !== b && (b = Cb(b), null !== b && Fc(b)), a;
      a.eventSystemFlags |= d;
      b = a.targetContainers;
      null !== e && -1 === b.indexOf(e) && b.push(e);
      return a;
    }
    function Uc(a, b, c, d, e) {
      switch (b) {
        case "focusin":
          return Lc = Tc(Lc, a, b, c, d, e), true;
        case "dragenter":
          return Mc = Tc(Mc, a, b, c, d, e), true;
        case "mouseover":
          return Nc = Tc(Nc, a, b, c, d, e), true;
        case "pointerover":
          var f = e.pointerId;
          Oc.set(f, Tc(Oc.get(f) || null, a, b, c, d, e));
          return true;
        case "gotpointercapture":
          return f = e.pointerId, Pc.set(f, Tc(Pc.get(f) || null, a, b, c, d, e)), true;
      }
      return false;
    }
    function Vc(a) {
      var b = Wc(a.target);
      if (null !== b) {
        var c = Vb(b);
        if (null !== c) {
          if (b = c.tag, 13 === b) {
            if (b = Wb(c), null !== b) {
              a.blockedOn = b;
              Ic(a.priority, function() {
                Gc(c);
              });
              return;
            }
          } else if (3 === b && c.stateNode.current.memoizedState.isDehydrated) {
            a.blockedOn = 3 === c.tag ? c.stateNode.containerInfo : null;
            return;
          }
        }
      }
      a.blockedOn = null;
    }
    function Xc(a) {
      if (null !== a.blockedOn) return false;
      for (var b = a.targetContainers; 0 < b.length; ) {
        var c = Yc(a.domEventName, a.eventSystemFlags, b[0], a.nativeEvent);
        if (null === c) {
          c = a.nativeEvent;
          var d = new c.constructor(c.type, c);
          wb = d;
          c.target.dispatchEvent(d);
          wb = null;
        } else return b = Cb(c), null !== b && Fc(b), a.blockedOn = c, false;
        b.shift();
      }
      return true;
    }
    function Zc(a, b, c) {
      Xc(a) && c.delete(b);
    }
    function $c() {
      Jc = false;
      null !== Lc && Xc(Lc) && (Lc = null);
      null !== Mc && Xc(Mc) && (Mc = null);
      null !== Nc && Xc(Nc) && (Nc = null);
      Oc.forEach(Zc);
      Pc.forEach(Zc);
    }
    function ad(a, b) {
      a.blockedOn === b && (a.blockedOn = null, Jc || (Jc = true, ca.unstable_scheduleCallback(ca.unstable_NormalPriority, $c)));
    }
    function bd(a) {
      function b(b2) {
        return ad(b2, a);
      }
      if (0 < Kc.length) {
        ad(Kc[0], a);
        for (var c = 1; c < Kc.length; c++) {
          var d = Kc[c];
          d.blockedOn === a && (d.blockedOn = null);
        }
      }
      null !== Lc && ad(Lc, a);
      null !== Mc && ad(Mc, a);
      null !== Nc && ad(Nc, a);
      Oc.forEach(b);
      Pc.forEach(b);
      for (c = 0; c < Qc.length; c++) d = Qc[c], d.blockedOn === a && (d.blockedOn = null);
      for (; 0 < Qc.length && (c = Qc[0], null === c.blockedOn); ) Vc(c), null === c.blockedOn && Qc.shift();
    }
    var cd = ua.ReactCurrentBatchConfig, dd = true;
    function ed(a, b, c, d) {
      var e = C, f = cd.transition;
      cd.transition = null;
      try {
        C = 1, fd(a, b, c, d);
      } finally {
        C = e, cd.transition = f;
      }
    }
    function gd(a, b, c, d) {
      var e = C, f = cd.transition;
      cd.transition = null;
      try {
        C = 4, fd(a, b, c, d);
      } finally {
        C = e, cd.transition = f;
      }
    }
    function fd(a, b, c, d) {
      if (dd) {
        var e = Yc(a, b, c, d);
        if (null === e) hd(a, b, d, id2, c), Sc(a, d);
        else if (Uc(e, a, b, c, d)) d.stopPropagation();
        else if (Sc(a, d), b & 4 && -1 < Rc.indexOf(a)) {
          for (; null !== e; ) {
            var f = Cb(e);
            null !== f && Ec(f);
            f = Yc(a, b, c, d);
            null === f && hd(a, b, d, id2, c);
            if (f === e) break;
            e = f;
          }
          null !== e && d.stopPropagation();
        } else hd(a, b, d, null, c);
      }
    }
    var id2 = null;
    function Yc(a, b, c, d) {
      id2 = null;
      a = xb(d);
      a = Wc(a);
      if (null !== a) if (b = Vb(a), null === b) a = null;
      else if (c = b.tag, 13 === c) {
        a = Wb(b);
        if (null !== a) return a;
        a = null;
      } else if (3 === c) {
        if (b.stateNode.current.memoizedState.isDehydrated) return 3 === b.tag ? b.stateNode.containerInfo : null;
        a = null;
      } else b !== a && (a = null);
      id2 = a;
      return null;
    }
    function jd(a) {
      switch (a) {
        case "cancel":
        case "click":
        case "close":
        case "contextmenu":
        case "copy":
        case "cut":
        case "auxclick":
        case "dblclick":
        case "dragend":
        case "dragstart":
        case "drop":
        case "focusin":
        case "focusout":
        case "input":
        case "invalid":
        case "keydown":
        case "keypress":
        case "keyup":
        case "mousedown":
        case "mouseup":
        case "paste":
        case "pause":
        case "play":
        case "pointercancel":
        case "pointerdown":
        case "pointerup":
        case "ratechange":
        case "reset":
        case "resize":
        case "seeked":
        case "submit":
        case "touchcancel":
        case "touchend":
        case "touchstart":
        case "volumechange":
        case "change":
        case "selectionchange":
        case "textInput":
        case "compositionstart":
        case "compositionend":
        case "compositionupdate":
        case "beforeblur":
        case "afterblur":
        case "beforeinput":
        case "blur":
        case "fullscreenchange":
        case "focus":
        case "hashchange":
        case "popstate":
        case "select":
        case "selectstart":
          return 1;
        case "drag":
        case "dragenter":
        case "dragexit":
        case "dragleave":
        case "dragover":
        case "mousemove":
        case "mouseout":
        case "mouseover":
        case "pointermove":
        case "pointerout":
        case "pointerover":
        case "scroll":
        case "toggle":
        case "touchmove":
        case "wheel":
        case "mouseenter":
        case "mouseleave":
        case "pointerenter":
        case "pointerleave":
          return 4;
        case "message":
          switch (ec()) {
            case fc:
              return 1;
            case gc:
              return 4;
            case hc:
            case ic:
              return 16;
            case jc:
              return 536870912;
            default:
              return 16;
          }
        default:
          return 16;
      }
    }
    var kd = null, ld = null, md = null;
    function nd() {
      if (md) return md;
      var a, b = ld, c = b.length, d, e = "value" in kd ? kd.value : kd.textContent, f = e.length;
      for (a = 0; a < c && b[a] === e[a]; a++) ;
      var g = c - a;
      for (d = 1; d <= g && b[c - d] === e[f - d]; d++) ;
      return md = e.slice(a, 1 < d ? 1 - d : void 0);
    }
    function od(a) {
      var b = a.keyCode;
      "charCode" in a ? (a = a.charCode, 0 === a && 13 === b && (a = 13)) : a = b;
      10 === a && (a = 13);
      return 32 <= a || 13 === a ? a : 0;
    }
    function pd() {
      return true;
    }
    function qd() {
      return false;
    }
    function rd(a) {
      function b(b2, d, e, f, g) {
        this._reactName = b2;
        this._targetInst = e;
        this.type = d;
        this.nativeEvent = f;
        this.target = g;
        this.currentTarget = null;
        for (var c in a) a.hasOwnProperty(c) && (b2 = a[c], this[c] = b2 ? b2(f) : f[c]);
        this.isDefaultPrevented = (null != f.defaultPrevented ? f.defaultPrevented : false === f.returnValue) ? pd : qd;
        this.isPropagationStopped = qd;
        return this;
      }
      A(b.prototype, { preventDefault: function() {
        this.defaultPrevented = true;
        var a2 = this.nativeEvent;
        a2 && (a2.preventDefault ? a2.preventDefault() : "unknown" !== typeof a2.returnValue && (a2.returnValue = false), this.isDefaultPrevented = pd);
      }, stopPropagation: function() {
        var a2 = this.nativeEvent;
        a2 && (a2.stopPropagation ? a2.stopPropagation() : "unknown" !== typeof a2.cancelBubble && (a2.cancelBubble = true), this.isPropagationStopped = pd);
      }, persist: function() {
      }, isPersistent: pd });
      return b;
    }
    var sd = { eventPhase: 0, bubbles: 0, cancelable: 0, timeStamp: function(a) {
      return a.timeStamp || Date.now();
    }, defaultPrevented: 0, isTrusted: 0 }, td = rd(sd), ud = A({}, sd, { view: 0, detail: 0 }), vd = rd(ud), wd, xd, yd, Ad = A({}, ud, { screenX: 0, screenY: 0, clientX: 0, clientY: 0, pageX: 0, pageY: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, getModifierState: zd, button: 0, buttons: 0, relatedTarget: function(a) {
      return void 0 === a.relatedTarget ? a.fromElement === a.srcElement ? a.toElement : a.fromElement : a.relatedTarget;
    }, movementX: function(a) {
      if ("movementX" in a) return a.movementX;
      a !== yd && (yd && "mousemove" === a.type ? (wd = a.screenX - yd.screenX, xd = a.screenY - yd.screenY) : xd = wd = 0, yd = a);
      return wd;
    }, movementY: function(a) {
      return "movementY" in a ? a.movementY : xd;
    } }), Bd = rd(Ad), Cd = A({}, Ad, { dataTransfer: 0 }), Dd = rd(Cd), Ed = A({}, ud, { relatedTarget: 0 }), Fd = rd(Ed), Gd = A({}, sd, { animationName: 0, elapsedTime: 0, pseudoElement: 0 }), Hd = rd(Gd), Id = A({}, sd, { clipboardData: function(a) {
      return "clipboardData" in a ? a.clipboardData : window.clipboardData;
    } }), Jd = rd(Id), Kd = A({}, sd, { data: 0 }), Ld = rd(Kd), Md = {
      Esc: "Escape",
      Spacebar: " ",
      Left: "ArrowLeft",
      Up: "ArrowUp",
      Right: "ArrowRight",
      Down: "ArrowDown",
      Del: "Delete",
      Win: "OS",
      Menu: "ContextMenu",
      Apps: "ContextMenu",
      Scroll: "ScrollLock",
      MozPrintableKey: "Unidentified"
    }, Nd = {
      8: "Backspace",
      9: "Tab",
      12: "Clear",
      13: "Enter",
      16: "Shift",
      17: "Control",
      18: "Alt",
      19: "Pause",
      20: "CapsLock",
      27: "Escape",
      32: " ",
      33: "PageUp",
      34: "PageDown",
      35: "End",
      36: "Home",
      37: "ArrowLeft",
      38: "ArrowUp",
      39: "ArrowRight",
      40: "ArrowDown",
      45: "Insert",
      46: "Delete",
      112: "F1",
      113: "F2",
      114: "F3",
      115: "F4",
      116: "F5",
      117: "F6",
      118: "F7",
      119: "F8",
      120: "F9",
      121: "F10",
      122: "F11",
      123: "F12",
      144: "NumLock",
      145: "ScrollLock",
      224: "Meta"
    }, Od = { Alt: "altKey", Control: "ctrlKey", Meta: "metaKey", Shift: "shiftKey" };
    function Pd(a) {
      var b = this.nativeEvent;
      return b.getModifierState ? b.getModifierState(a) : (a = Od[a]) ? !!b[a] : false;
    }
    function zd() {
      return Pd;
    }
    var Qd = A({}, ud, { key: function(a) {
      if (a.key) {
        var b = Md[a.key] || a.key;
        if ("Unidentified" !== b) return b;
      }
      return "keypress" === a.type ? (a = od(a), 13 === a ? "Enter" : String.fromCharCode(a)) : "keydown" === a.type || "keyup" === a.type ? Nd[a.keyCode] || "Unidentified" : "";
    }, code: 0, location: 0, ctrlKey: 0, shiftKey: 0, altKey: 0, metaKey: 0, repeat: 0, locale: 0, getModifierState: zd, charCode: function(a) {
      return "keypress" === a.type ? od(a) : 0;
    }, keyCode: function(a) {
      return "keydown" === a.type || "keyup" === a.type ? a.keyCode : 0;
    }, which: function(a) {
      return "keypress" === a.type ? od(a) : "keydown" === a.type || "keyup" === a.type ? a.keyCode : 0;
    } }), Rd = rd(Qd), Sd = A({}, Ad, { pointerId: 0, width: 0, height: 0, pressure: 0, tangentialPressure: 0, tiltX: 0, tiltY: 0, twist: 0, pointerType: 0, isPrimary: 0 }), Td = rd(Sd), Ud = A({}, ud, { touches: 0, targetTouches: 0, changedTouches: 0, altKey: 0, metaKey: 0, ctrlKey: 0, shiftKey: 0, getModifierState: zd }), Vd = rd(Ud), Wd = A({}, sd, { propertyName: 0, elapsedTime: 0, pseudoElement: 0 }), Xd = rd(Wd), Yd = A({}, Ad, {
      deltaX: function(a) {
        return "deltaX" in a ? a.deltaX : "wheelDeltaX" in a ? -a.wheelDeltaX : 0;
      },
      deltaY: function(a) {
        return "deltaY" in a ? a.deltaY : "wheelDeltaY" in a ? -a.wheelDeltaY : "wheelDelta" in a ? -a.wheelDelta : 0;
      },
      deltaZ: 0,
      deltaMode: 0
    }), Zd = rd(Yd), $d = [9, 13, 27, 32], ae = ia && "CompositionEvent" in window, be = null;
    ia && "documentMode" in document && (be = document.documentMode);
    var ce = ia && "TextEvent" in window && !be, de = ia && (!ae || be && 8 < be && 11 >= be), ee = String.fromCharCode(32), fe = false;
    function ge(a, b) {
      switch (a) {
        case "keyup":
          return -1 !== $d.indexOf(b.keyCode);
        case "keydown":
          return 229 !== b.keyCode;
        case "keypress":
        case "mousedown":
        case "focusout":
          return true;
        default:
          return false;
      }
    }
    function he(a) {
      a = a.detail;
      return "object" === typeof a && "data" in a ? a.data : null;
    }
    var ie = false;
    function je(a, b) {
      switch (a) {
        case "compositionend":
          return he(b);
        case "keypress":
          if (32 !== b.which) return null;
          fe = true;
          return ee;
        case "textInput":
          return a = b.data, a === ee && fe ? null : a;
        default:
          return null;
      }
    }
    function ke(a, b) {
      if (ie) return "compositionend" === a || !ae && ge(a, b) ? (a = nd(), md = ld = kd = null, ie = false, a) : null;
      switch (a) {
        case "paste":
          return null;
        case "keypress":
          if (!(b.ctrlKey || b.altKey || b.metaKey) || b.ctrlKey && b.altKey) {
            if (b.char && 1 < b.char.length) return b.char;
            if (b.which) return String.fromCharCode(b.which);
          }
          return null;
        case "compositionend":
          return de && "ko" !== b.locale ? null : b.data;
        default:
          return null;
      }
    }
    var le = { color: true, date: true, datetime: true, "datetime-local": true, email: true, month: true, number: true, password: true, range: true, search: true, tel: true, text: true, time: true, url: true, week: true };
    function me(a) {
      var b = a && a.nodeName && a.nodeName.toLowerCase();
      return "input" === b ? !!le[a.type] : "textarea" === b ? true : false;
    }
    function ne(a, b, c, d) {
      Eb(d);
      b = oe(b, "onChange");
      0 < b.length && (c = new td("onChange", "change", null, c, d), a.push({ event: c, listeners: b }));
    }
    var pe = null, qe = null;
    function re(a) {
      se(a, 0);
    }
    function te(a) {
      var b = ue(a);
      if (Wa(b)) return a;
    }
    function ve(a, b) {
      if ("change" === a) return b;
    }
    var we = false;
    if (ia) {
      var xe;
      if (ia) {
        var ye = "oninput" in document;
        if (!ye) {
          var ze = document.createElement("div");
          ze.setAttribute("oninput", "return;");
          ye = "function" === typeof ze.oninput;
        }
        xe = ye;
      } else xe = false;
      we = xe && (!document.documentMode || 9 < document.documentMode);
    }
    function Ae() {
      pe && (pe.detachEvent("onpropertychange", Be), qe = pe = null);
    }
    function Be(a) {
      if ("value" === a.propertyName && te(qe)) {
        var b = [];
        ne(b, qe, a, xb(a));
        Jb(re, b);
      }
    }
    function Ce(a, b, c) {
      "focusin" === a ? (Ae(), pe = b, qe = c, pe.attachEvent("onpropertychange", Be)) : "focusout" === a && Ae();
    }
    function De(a) {
      if ("selectionchange" === a || "keyup" === a || "keydown" === a) return te(qe);
    }
    function Ee(a, b) {
      if ("click" === a) return te(b);
    }
    function Fe(a, b) {
      if ("input" === a || "change" === a) return te(b);
    }
    function Ge(a, b) {
      return a === b && (0 !== a || 1 / a === 1 / b) || a !== a && b !== b;
    }
    var He = "function" === typeof Object.is ? Object.is : Ge;
    function Ie(a, b) {
      if (He(a, b)) return true;
      if ("object" !== typeof a || null === a || "object" !== typeof b || null === b) return false;
      var c = Object.keys(a), d = Object.keys(b);
      if (c.length !== d.length) return false;
      for (d = 0; d < c.length; d++) {
        var e = c[d];
        if (!ja.call(b, e) || !He(a[e], b[e])) return false;
      }
      return true;
    }
    function Je(a) {
      for (; a && a.firstChild; ) a = a.firstChild;
      return a;
    }
    function Ke(a, b) {
      var c = Je(a);
      a = 0;
      for (var d; c; ) {
        if (3 === c.nodeType) {
          d = a + c.textContent.length;
          if (a <= b && d >= b) return { node: c, offset: b - a };
          a = d;
        }
        a: {
          for (; c; ) {
            if (c.nextSibling) {
              c = c.nextSibling;
              break a;
            }
            c = c.parentNode;
          }
          c = void 0;
        }
        c = Je(c);
      }
    }
    function Le(a, b) {
      return a && b ? a === b ? true : a && 3 === a.nodeType ? false : b && 3 === b.nodeType ? Le(a, b.parentNode) : "contains" in a ? a.contains(b) : a.compareDocumentPosition ? !!(a.compareDocumentPosition(b) & 16) : false : false;
    }
    function Me() {
      for (var a = window, b = Xa(); b instanceof a.HTMLIFrameElement; ) {
        try {
          var c = "string" === typeof b.contentWindow.location.href;
        } catch (d) {
          c = false;
        }
        if (c) a = b.contentWindow;
        else break;
        b = Xa(a.document);
      }
      return b;
    }
    function Ne(a) {
      var b = a && a.nodeName && a.nodeName.toLowerCase();
      return b && ("input" === b && ("text" === a.type || "search" === a.type || "tel" === a.type || "url" === a.type || "password" === a.type) || "textarea" === b || "true" === a.contentEditable);
    }
    function Oe(a) {
      var b = Me(), c = a.focusedElem, d = a.selectionRange;
      if (b !== c && c && c.ownerDocument && Le(c.ownerDocument.documentElement, c)) {
        if (null !== d && Ne(c)) {
          if (b = d.start, a = d.end, void 0 === a && (a = b), "selectionStart" in c) c.selectionStart = b, c.selectionEnd = Math.min(a, c.value.length);
          else if (a = (b = c.ownerDocument || document) && b.defaultView || window, a.getSelection) {
            a = a.getSelection();
            var e = c.textContent.length, f = Math.min(d.start, e);
            d = void 0 === d.end ? f : Math.min(d.end, e);
            !a.extend && f > d && (e = d, d = f, f = e);
            e = Ke(c, f);
            var g = Ke(
              c,
              d
            );
            e && g && (1 !== a.rangeCount || a.anchorNode !== e.node || a.anchorOffset !== e.offset || a.focusNode !== g.node || a.focusOffset !== g.offset) && (b = b.createRange(), b.setStart(e.node, e.offset), a.removeAllRanges(), f > d ? (a.addRange(b), a.extend(g.node, g.offset)) : (b.setEnd(g.node, g.offset), a.addRange(b)));
          }
        }
        b = [];
        for (a = c; a = a.parentNode; ) 1 === a.nodeType && b.push({ element: a, left: a.scrollLeft, top: a.scrollTop });
        "function" === typeof c.focus && c.focus();
        for (c = 0; c < b.length; c++) a = b[c], a.element.scrollLeft = a.left, a.element.scrollTop = a.top;
      }
    }
    var Pe = ia && "documentMode" in document && 11 >= document.documentMode, Qe = null, Re = null, Se = null, Te = false;
    function Ue(a, b, c) {
      var d = c.window === c ? c.document : 9 === c.nodeType ? c : c.ownerDocument;
      Te || null == Qe || Qe !== Xa(d) || (d = Qe, "selectionStart" in d && Ne(d) ? d = { start: d.selectionStart, end: d.selectionEnd } : (d = (d.ownerDocument && d.ownerDocument.defaultView || window).getSelection(), d = { anchorNode: d.anchorNode, anchorOffset: d.anchorOffset, focusNode: d.focusNode, focusOffset: d.focusOffset }), Se && Ie(Se, d) || (Se = d, d = oe(Re, "onSelect"), 0 < d.length && (b = new td("onSelect", "select", null, b, c), a.push({ event: b, listeners: d }), b.target = Qe)));
    }
    function Ve(a, b) {
      var c = {};
      c[a.toLowerCase()] = b.toLowerCase();
      c["Webkit" + a] = "webkit" + b;
      c["Moz" + a] = "moz" + b;
      return c;
    }
    var We = { animationend: Ve("Animation", "AnimationEnd"), animationiteration: Ve("Animation", "AnimationIteration"), animationstart: Ve("Animation", "AnimationStart"), transitionend: Ve("Transition", "TransitionEnd") }, Xe = {}, Ye = {};
    ia && (Ye = document.createElement("div").style, "AnimationEvent" in window || (delete We.animationend.animation, delete We.animationiteration.animation, delete We.animationstart.animation), "TransitionEvent" in window || delete We.transitionend.transition);
    function Ze(a) {
      if (Xe[a]) return Xe[a];
      if (!We[a]) return a;
      var b = We[a], c;
      for (c in b) if (b.hasOwnProperty(c) && c in Ye) return Xe[a] = b[c];
      return a;
    }
    var $e = Ze("animationend"), af = Ze("animationiteration"), bf = Ze("animationstart"), cf = Ze("transitionend"), df = /* @__PURE__ */ new Map(), ef = "abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");
    function ff(a, b) {
      df.set(a, b);
      fa(b, [a]);
    }
    for (var gf = 0; gf < ef.length; gf++) {
      var hf = ef[gf], jf = hf.toLowerCase(), kf = hf[0].toUpperCase() + hf.slice(1);
      ff(jf, "on" + kf);
    }
    ff($e, "onAnimationEnd");
    ff(af, "onAnimationIteration");
    ff(bf, "onAnimationStart");
    ff("dblclick", "onDoubleClick");
    ff("focusin", "onFocus");
    ff("focusout", "onBlur");
    ff(cf, "onTransitionEnd");
    ha("onMouseEnter", ["mouseout", "mouseover"]);
    ha("onMouseLeave", ["mouseout", "mouseover"]);
    ha("onPointerEnter", ["pointerout", "pointerover"]);
    ha("onPointerLeave", ["pointerout", "pointerover"]);
    fa("onChange", "change click focusin focusout input keydown keyup selectionchange".split(" "));
    fa("onSelect", "focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));
    fa("onBeforeInput", ["compositionend", "keypress", "textInput", "paste"]);
    fa("onCompositionEnd", "compositionend focusout keydown keypress keyup mousedown".split(" "));
    fa("onCompositionStart", "compositionstart focusout keydown keypress keyup mousedown".split(" "));
    fa("onCompositionUpdate", "compositionupdate focusout keydown keypress keyup mousedown".split(" "));
    var lf = "abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "), mf = new Set("cancel close invalid load scroll toggle".split(" ").concat(lf));
    function nf(a, b, c) {
      var d = a.type || "unknown-event";
      a.currentTarget = c;
      Ub(d, b, void 0, a);
      a.currentTarget = null;
    }
    function se(a, b) {
      b = 0 !== (b & 4);
      for (var c = 0; c < a.length; c++) {
        var d = a[c], e = d.event;
        d = d.listeners;
        a: {
          var f = void 0;
          if (b) for (var g = d.length - 1; 0 <= g; g--) {
            var h = d[g], k = h.instance, l = h.currentTarget;
            h = h.listener;
            if (k !== f && e.isPropagationStopped()) break a;
            nf(e, h, l);
            f = k;
          }
          else for (g = 0; g < d.length; g++) {
            h = d[g];
            k = h.instance;
            l = h.currentTarget;
            h = h.listener;
            if (k !== f && e.isPropagationStopped()) break a;
            nf(e, h, l);
            f = k;
          }
        }
      }
      if (Qb) throw a = Rb, Qb = false, Rb = null, a;
    }
    function D(a, b) {
      var c = b[of];
      void 0 === c && (c = b[of] = /* @__PURE__ */ new Set());
      var d = a + "__bubble";
      c.has(d) || (pf(b, a, 2, false), c.add(d));
    }
    function qf(a, b, c) {
      var d = 0;
      b && (d |= 4);
      pf(c, a, d, b);
    }
    var rf = "_reactListening" + Math.random().toString(36).slice(2);
    function sf(a) {
      if (!a[rf]) {
        a[rf] = true;
        da.forEach(function(b2) {
          "selectionchange" !== b2 && (mf.has(b2) || qf(b2, false, a), qf(b2, true, a));
        });
        var b = 9 === a.nodeType ? a : a.ownerDocument;
        null === b || b[rf] || (b[rf] = true, qf("selectionchange", false, b));
      }
    }
    function pf(a, b, c, d) {
      switch (jd(b)) {
        case 1:
          var e = ed;
          break;
        case 4:
          e = gd;
          break;
        default:
          e = fd;
      }
      c = e.bind(null, b, c, a);
      e = void 0;
      !Lb || "touchstart" !== b && "touchmove" !== b && "wheel" !== b || (e = true);
      d ? void 0 !== e ? a.addEventListener(b, c, { capture: true, passive: e }) : a.addEventListener(b, c, true) : void 0 !== e ? a.addEventListener(b, c, { passive: e }) : a.addEventListener(b, c, false);
    }
    function hd(a, b, c, d, e) {
      var f = d;
      if (0 === (b & 1) && 0 === (b & 2) && null !== d) a: for (; ; ) {
        if (null === d) return;
        var g = d.tag;
        if (3 === g || 4 === g) {
          var h = d.stateNode.containerInfo;
          if (h === e || 8 === h.nodeType && h.parentNode === e) break;
          if (4 === g) for (g = d.return; null !== g; ) {
            var k = g.tag;
            if (3 === k || 4 === k) {
              if (k = g.stateNode.containerInfo, k === e || 8 === k.nodeType && k.parentNode === e) return;
            }
            g = g.return;
          }
          for (; null !== h; ) {
            g = Wc(h);
            if (null === g) return;
            k = g.tag;
            if (5 === k || 6 === k) {
              d = f = g;
              continue a;
            }
            h = h.parentNode;
          }
        }
        d = d.return;
      }
      Jb(function() {
        var d2 = f, e2 = xb(c), g2 = [];
        a: {
          var h2 = df.get(a);
          if (void 0 !== h2) {
            var k2 = td, n = a;
            switch (a) {
              case "keypress":
                if (0 === od(c)) break a;
              case "keydown":
              case "keyup":
                k2 = Rd;
                break;
              case "focusin":
                n = "focus";
                k2 = Fd;
                break;
              case "focusout":
                n = "blur";
                k2 = Fd;
                break;
              case "beforeblur":
              case "afterblur":
                k2 = Fd;
                break;
              case "click":
                if (2 === c.button) break a;
              case "auxclick":
              case "dblclick":
              case "mousedown":
              case "mousemove":
              case "mouseup":
              case "mouseout":
              case "mouseover":
              case "contextmenu":
                k2 = Bd;
                break;
              case "drag":
              case "dragend":
              case "dragenter":
              case "dragexit":
              case "dragleave":
              case "dragover":
              case "dragstart":
              case "drop":
                k2 = Dd;
                break;
              case "touchcancel":
              case "touchend":
              case "touchmove":
              case "touchstart":
                k2 = Vd;
                break;
              case $e:
              case af:
              case bf:
                k2 = Hd;
                break;
              case cf:
                k2 = Xd;
                break;
              case "scroll":
                k2 = vd;
                break;
              case "wheel":
                k2 = Zd;
                break;
              case "copy":
              case "cut":
              case "paste":
                k2 = Jd;
                break;
              case "gotpointercapture":
              case "lostpointercapture":
              case "pointercancel":
              case "pointerdown":
              case "pointermove":
              case "pointerout":
              case "pointerover":
              case "pointerup":
                k2 = Td;
            }
            var t = 0 !== (b & 4), J = !t && "scroll" === a, x = t ? null !== h2 ? h2 + "Capture" : null : h2;
            t = [];
            for (var w = d2, u; null !== w; ) {
              u = w;
              var F = u.stateNode;
              5 === u.tag && null !== F && (u = F, null !== x && (F = Kb(w, x), null != F && t.push(tf(w, F, u))));
              if (J) break;
              w = w.return;
            }
            0 < t.length && (h2 = new k2(h2, n, null, c, e2), g2.push({ event: h2, listeners: t }));
          }
        }
        if (0 === (b & 7)) {
          a: {
            h2 = "mouseover" === a || "pointerover" === a;
            k2 = "mouseout" === a || "pointerout" === a;
            if (h2 && c !== wb && (n = c.relatedTarget || c.fromElement) && (Wc(n) || n[uf])) break a;
            if (k2 || h2) {
              h2 = e2.window === e2 ? e2 : (h2 = e2.ownerDocument) ? h2.defaultView || h2.parentWindow : window;
              if (k2) {
                if (n = c.relatedTarget || c.toElement, k2 = d2, n = n ? Wc(n) : null, null !== n && (J = Vb(n), n !== J || 5 !== n.tag && 6 !== n.tag)) n = null;
              } else k2 = null, n = d2;
              if (k2 !== n) {
                t = Bd;
                F = "onMouseLeave";
                x = "onMouseEnter";
                w = "mouse";
                if ("pointerout" === a || "pointerover" === a) t = Td, F = "onPointerLeave", x = "onPointerEnter", w = "pointer";
                J = null == k2 ? h2 : ue(k2);
                u = null == n ? h2 : ue(n);
                h2 = new t(F, w + "leave", k2, c, e2);
                h2.target = J;
                h2.relatedTarget = u;
                F = null;
                Wc(e2) === d2 && (t = new t(x, w + "enter", n, c, e2), t.target = u, t.relatedTarget = J, F = t);
                J = F;
                if (k2 && n) b: {
                  t = k2;
                  x = n;
                  w = 0;
                  for (u = t; u; u = vf(u)) w++;
                  u = 0;
                  for (F = x; F; F = vf(F)) u++;
                  for (; 0 < w - u; ) t = vf(t), w--;
                  for (; 0 < u - w; ) x = vf(x), u--;
                  for (; w--; ) {
                    if (t === x || null !== x && t === x.alternate) break b;
                    t = vf(t);
                    x = vf(x);
                  }
                  t = null;
                }
                else t = null;
                null !== k2 && wf(g2, h2, k2, t, false);
                null !== n && null !== J && wf(g2, J, n, t, true);
              }
            }
          }
          a: {
            h2 = d2 ? ue(d2) : window;
            k2 = h2.nodeName && h2.nodeName.toLowerCase();
            if ("select" === k2 || "input" === k2 && "file" === h2.type) var na = ve;
            else if (me(h2)) if (we) na = Fe;
            else {
              na = De;
              var xa = Ce;
            }
            else (k2 = h2.nodeName) && "input" === k2.toLowerCase() && ("checkbox" === h2.type || "radio" === h2.type) && (na = Ee);
            if (na && (na = na(a, d2))) {
              ne(g2, na, c, e2);
              break a;
            }
            xa && xa(a, h2, d2);
            "focusout" === a && (xa = h2._wrapperState) && xa.controlled && "number" === h2.type && cb(h2, "number", h2.value);
          }
          xa = d2 ? ue(d2) : window;
          switch (a) {
            case "focusin":
              if (me(xa) || "true" === xa.contentEditable) Qe = xa, Re = d2, Se = null;
              break;
            case "focusout":
              Se = Re = Qe = null;
              break;
            case "mousedown":
              Te = true;
              break;
            case "contextmenu":
            case "mouseup":
            case "dragend":
              Te = false;
              Ue(g2, c, e2);
              break;
            case "selectionchange":
              if (Pe) break;
            case "keydown":
            case "keyup":
              Ue(g2, c, e2);
          }
          var $a;
          if (ae) b: {
            switch (a) {
              case "compositionstart":
                var ba = "onCompositionStart";
                break b;
              case "compositionend":
                ba = "onCompositionEnd";
                break b;
              case "compositionupdate":
                ba = "onCompositionUpdate";
                break b;
            }
            ba = void 0;
          }
          else ie ? ge(a, c) && (ba = "onCompositionEnd") : "keydown" === a && 229 === c.keyCode && (ba = "onCompositionStart");
          ba && (de && "ko" !== c.locale && (ie || "onCompositionStart" !== ba ? "onCompositionEnd" === ba && ie && ($a = nd()) : (kd = e2, ld = "value" in kd ? kd.value : kd.textContent, ie = true)), xa = oe(d2, ba), 0 < xa.length && (ba = new Ld(ba, a, null, c, e2), g2.push({ event: ba, listeners: xa }), $a ? ba.data = $a : ($a = he(c), null !== $a && (ba.data = $a))));
          if ($a = ce ? je(a, c) : ke(a, c)) d2 = oe(d2, "onBeforeInput"), 0 < d2.length && (e2 = new Ld("onBeforeInput", "beforeinput", null, c, e2), g2.push({ event: e2, listeners: d2 }), e2.data = $a);
        }
        se(g2, b);
      });
    }
    function tf(a, b, c) {
      return { instance: a, listener: b, currentTarget: c };
    }
    function oe(a, b) {
      for (var c = b + "Capture", d = []; null !== a; ) {
        var e = a, f = e.stateNode;
        5 === e.tag && null !== f && (e = f, f = Kb(a, c), null != f && d.unshift(tf(a, f, e)), f = Kb(a, b), null != f && d.push(tf(a, f, e)));
        a = a.return;
      }
      return d;
    }
    function vf(a) {
      if (null === a) return null;
      do
        a = a.return;
      while (a && 5 !== a.tag);
      return a ? a : null;
    }
    function wf(a, b, c, d, e) {
      for (var f = b._reactName, g = []; null !== c && c !== d; ) {
        var h = c, k = h.alternate, l = h.stateNode;
        if (null !== k && k === d) break;
        5 === h.tag && null !== l && (h = l, e ? (k = Kb(c, f), null != k && g.unshift(tf(c, k, h))) : e || (k = Kb(c, f), null != k && g.push(tf(c, k, h))));
        c = c.return;
      }
      0 !== g.length && a.push({ event: b, listeners: g });
    }
    var xf = /\r\n?/g, yf = /\u0000|\uFFFD/g;
    function zf(a) {
      return ("string" === typeof a ? a : "" + a).replace(xf, "\n").replace(yf, "");
    }
    function Af(a, b, c) {
      b = zf(b);
      if (zf(a) !== b && c) throw Error(p(425));
    }
    function Bf() {
    }
    var Cf = null, Df = null;
    function Ef(a, b) {
      return "textarea" === a || "noscript" === a || "string" === typeof b.children || "number" === typeof b.children || "object" === typeof b.dangerouslySetInnerHTML && null !== b.dangerouslySetInnerHTML && null != b.dangerouslySetInnerHTML.__html;
    }
    var Ff = "function" === typeof setTimeout ? setTimeout : void 0, Gf = "function" === typeof clearTimeout ? clearTimeout : void 0, Hf = "function" === typeof Promise ? Promise : void 0, Jf = "function" === typeof queueMicrotask ? queueMicrotask : "undefined" !== typeof Hf ? function(a) {
      return Hf.resolve(null).then(a).catch(If);
    } : Ff;
    function If(a) {
      setTimeout(function() {
        throw a;
      });
    }
    function Kf(a, b) {
      var c = b, d = 0;
      do {
        var e = c.nextSibling;
        a.removeChild(c);
        if (e && 8 === e.nodeType) if (c = e.data, "/$" === c) {
          if (0 === d) {
            a.removeChild(e);
            bd(b);
            return;
          }
          d--;
        } else "$" !== c && "$?" !== c && "$!" !== c || d++;
        c = e;
      } while (c);
      bd(b);
    }
    function Lf(a) {
      for (; null != a; a = a.nextSibling) {
        var b = a.nodeType;
        if (1 === b || 3 === b) break;
        if (8 === b) {
          b = a.data;
          if ("$" === b || "$!" === b || "$?" === b) break;
          if ("/$" === b) return null;
        }
      }
      return a;
    }
    function Mf(a) {
      a = a.previousSibling;
      for (var b = 0; a; ) {
        if (8 === a.nodeType) {
          var c = a.data;
          if ("$" === c || "$!" === c || "$?" === c) {
            if (0 === b) return a;
            b--;
          } else "/$" === c && b++;
        }
        a = a.previousSibling;
      }
      return null;
    }
    var Nf = Math.random().toString(36).slice(2), Of = "__reactFiber$" + Nf, Pf = "__reactProps$" + Nf, uf = "__reactContainer$" + Nf, of = "__reactEvents$" + Nf, Qf = "__reactListeners$" + Nf, Rf = "__reactHandles$" + Nf;
    function Wc(a) {
      var b = a[Of];
      if (b) return b;
      for (var c = a.parentNode; c; ) {
        if (b = c[uf] || c[Of]) {
          c = b.alternate;
          if (null !== b.child || null !== c && null !== c.child) for (a = Mf(a); null !== a; ) {
            if (c = a[Of]) return c;
            a = Mf(a);
          }
          return b;
        }
        a = c;
        c = a.parentNode;
      }
      return null;
    }
    function Cb(a) {
      a = a[Of] || a[uf];
      return !a || 5 !== a.tag && 6 !== a.tag && 13 !== a.tag && 3 !== a.tag ? null : a;
    }
    function ue(a) {
      if (5 === a.tag || 6 === a.tag) return a.stateNode;
      throw Error(p(33));
    }
    function Db(a) {
      return a[Pf] || null;
    }
    var Sf = [], Tf = -1;
    function Uf(a) {
      return { current: a };
    }
    function E(a) {
      0 > Tf || (a.current = Sf[Tf], Sf[Tf] = null, Tf--);
    }
    function G(a, b) {
      Tf++;
      Sf[Tf] = a.current;
      a.current = b;
    }
    var Vf = {}, H = Uf(Vf), Wf = Uf(false), Xf = Vf;
    function Yf(a, b) {
      var c = a.type.contextTypes;
      if (!c) return Vf;
      var d = a.stateNode;
      if (d && d.__reactInternalMemoizedUnmaskedChildContext === b) return d.__reactInternalMemoizedMaskedChildContext;
      var e = {}, f;
      for (f in c) e[f] = b[f];
      d && (a = a.stateNode, a.__reactInternalMemoizedUnmaskedChildContext = b, a.__reactInternalMemoizedMaskedChildContext = e);
      return e;
    }
    function Zf(a) {
      a = a.childContextTypes;
      return null !== a && void 0 !== a;
    }
    function $f() {
      E(Wf);
      E(H);
    }
    function ag(a, b, c) {
      if (H.current !== Vf) throw Error(p(168));
      G(H, b);
      G(Wf, c);
    }
    function bg(a, b, c) {
      var d = a.stateNode;
      b = b.childContextTypes;
      if ("function" !== typeof d.getChildContext) return c;
      d = d.getChildContext();
      for (var e in d) if (!(e in b)) throw Error(p(108, Ra(a) || "Unknown", e));
      return A({}, c, d);
    }
    function cg(a) {
      a = (a = a.stateNode) && a.__reactInternalMemoizedMergedChildContext || Vf;
      Xf = H.current;
      G(H, a);
      G(Wf, Wf.current);
      return true;
    }
    function dg(a, b, c) {
      var d = a.stateNode;
      if (!d) throw Error(p(169));
      c ? (a = bg(a, b, Xf), d.__reactInternalMemoizedMergedChildContext = a, E(Wf), E(H), G(H, a)) : E(Wf);
      G(Wf, c);
    }
    var eg = null, fg = false, gg = false;
    function hg(a) {
      null === eg ? eg = [a] : eg.push(a);
    }
    function ig(a) {
      fg = true;
      hg(a);
    }
    function jg() {
      if (!gg && null !== eg) {
        gg = true;
        var a = 0, b = C;
        try {
          var c = eg;
          for (C = 1; a < c.length; a++) {
            var d = c[a];
            do
              d = d(true);
            while (null !== d);
          }
          eg = null;
          fg = false;
        } catch (e) {
          throw null !== eg && (eg = eg.slice(a + 1)), ac(fc, jg), e;
        } finally {
          C = b, gg = false;
        }
      }
      return null;
    }
    var kg = [], lg = 0, mg = null, ng = 0, og = [], pg = 0, qg = null, rg = 1, sg = "";
    function tg(a, b) {
      kg[lg++] = ng;
      kg[lg++] = mg;
      mg = a;
      ng = b;
    }
    function ug(a, b, c) {
      og[pg++] = rg;
      og[pg++] = sg;
      og[pg++] = qg;
      qg = a;
      var d = rg;
      a = sg;
      var e = 32 - oc(d) - 1;
      d &= ~(1 << e);
      c += 1;
      var f = 32 - oc(b) + e;
      if (30 < f) {
        var g = e - e % 5;
        f = (d & (1 << g) - 1).toString(32);
        d >>= g;
        e -= g;
        rg = 1 << 32 - oc(b) + e | c << e | d;
        sg = f + a;
      } else rg = 1 << f | c << e | d, sg = a;
    }
    function vg(a) {
      null !== a.return && (tg(a, 1), ug(a, 1, 0));
    }
    function wg(a) {
      for (; a === mg; ) mg = kg[--lg], kg[lg] = null, ng = kg[--lg], kg[lg] = null;
      for (; a === qg; ) qg = og[--pg], og[pg] = null, sg = og[--pg], og[pg] = null, rg = og[--pg], og[pg] = null;
    }
    var xg = null, yg = null, I = false, zg = null;
    function Ag(a, b) {
      var c = Bg(5, null, null, 0);
      c.elementType = "DELETED";
      c.stateNode = b;
      c.return = a;
      b = a.deletions;
      null === b ? (a.deletions = [c], a.flags |= 16) : b.push(c);
    }
    function Cg(a, b) {
      switch (a.tag) {
        case 5:
          var c = a.type;
          b = 1 !== b.nodeType || c.toLowerCase() !== b.nodeName.toLowerCase() ? null : b;
          return null !== b ? (a.stateNode = b, xg = a, yg = Lf(b.firstChild), true) : false;
        case 6:
          return b = "" === a.pendingProps || 3 !== b.nodeType ? null : b, null !== b ? (a.stateNode = b, xg = a, yg = null, true) : false;
        case 13:
          return b = 8 !== b.nodeType ? null : b, null !== b ? (c = null !== qg ? { id: rg, overflow: sg } : null, a.memoizedState = { dehydrated: b, treeContext: c, retryLane: 1073741824 }, c = Bg(18, null, null, 0), c.stateNode = b, c.return = a, a.child = c, xg = a, yg = null, true) : false;
        default:
          return false;
      }
    }
    function Dg(a) {
      return 0 !== (a.mode & 1) && 0 === (a.flags & 128);
    }
    function Eg(a) {
      if (I) {
        var b = yg;
        if (b) {
          var c = b;
          if (!Cg(a, b)) {
            if (Dg(a)) throw Error(p(418));
            b = Lf(c.nextSibling);
            var d = xg;
            b && Cg(a, b) ? Ag(d, c) : (a.flags = a.flags & -4097 | 2, I = false, xg = a);
          }
        } else {
          if (Dg(a)) throw Error(p(418));
          a.flags = a.flags & -4097 | 2;
          I = false;
          xg = a;
        }
      }
    }
    function Fg(a) {
      for (a = a.return; null !== a && 5 !== a.tag && 3 !== a.tag && 13 !== a.tag; ) a = a.return;
      xg = a;
    }
    function Gg(a) {
      if (a !== xg) return false;
      if (!I) return Fg(a), I = true, false;
      var b;
      (b = 3 !== a.tag) && !(b = 5 !== a.tag) && (b = a.type, b = "head" !== b && "body" !== b && !Ef(a.type, a.memoizedProps));
      if (b && (b = yg)) {
        if (Dg(a)) throw Hg(), Error(p(418));
        for (; b; ) Ag(a, b), b = Lf(b.nextSibling);
      }
      Fg(a);
      if (13 === a.tag) {
        a = a.memoizedState;
        a = null !== a ? a.dehydrated : null;
        if (!a) throw Error(p(317));
        a: {
          a = a.nextSibling;
          for (b = 0; a; ) {
            if (8 === a.nodeType) {
              var c = a.data;
              if ("/$" === c) {
                if (0 === b) {
                  yg = Lf(a.nextSibling);
                  break a;
                }
                b--;
              } else "$" !== c && "$!" !== c && "$?" !== c || b++;
            }
            a = a.nextSibling;
          }
          yg = null;
        }
      } else yg = xg ? Lf(a.stateNode.nextSibling) : null;
      return true;
    }
    function Hg() {
      for (var a = yg; a; ) a = Lf(a.nextSibling);
    }
    function Ig() {
      yg = xg = null;
      I = false;
    }
    function Jg(a) {
      null === zg ? zg = [a] : zg.push(a);
    }
    var Kg = ua.ReactCurrentBatchConfig;
    function Lg(a, b, c) {
      a = c.ref;
      if (null !== a && "function" !== typeof a && "object" !== typeof a) {
        if (c._owner) {
          c = c._owner;
          if (c) {
            if (1 !== c.tag) throw Error(p(309));
            var d = c.stateNode;
          }
          if (!d) throw Error(p(147, a));
          var e = d, f = "" + a;
          if (null !== b && null !== b.ref && "function" === typeof b.ref && b.ref._stringRef === f) return b.ref;
          b = function(a2) {
            var b2 = e.refs;
            null === a2 ? delete b2[f] : b2[f] = a2;
          };
          b._stringRef = f;
          return b;
        }
        if ("string" !== typeof a) throw Error(p(284));
        if (!c._owner) throw Error(p(290, a));
      }
      return a;
    }
    function Mg(a, b) {
      a = Object.prototype.toString.call(b);
      throw Error(p(31, "[object Object]" === a ? "object with keys {" + Object.keys(b).join(", ") + "}" : a));
    }
    function Ng(a) {
      var b = a._init;
      return b(a._payload);
    }
    function Og(a) {
      function b(b2, c2) {
        if (a) {
          var d2 = b2.deletions;
          null === d2 ? (b2.deletions = [c2], b2.flags |= 16) : d2.push(c2);
        }
      }
      function c(c2, d2) {
        if (!a) return null;
        for (; null !== d2; ) b(c2, d2), d2 = d2.sibling;
        return null;
      }
      function d(a2, b2) {
        for (a2 = /* @__PURE__ */ new Map(); null !== b2; ) null !== b2.key ? a2.set(b2.key, b2) : a2.set(b2.index, b2), b2 = b2.sibling;
        return a2;
      }
      function e(a2, b2) {
        a2 = Pg(a2, b2);
        a2.index = 0;
        a2.sibling = null;
        return a2;
      }
      function f(b2, c2, d2) {
        b2.index = d2;
        if (!a) return b2.flags |= 1048576, c2;
        d2 = b2.alternate;
        if (null !== d2) return d2 = d2.index, d2 < c2 ? (b2.flags |= 2, c2) : d2;
        b2.flags |= 2;
        return c2;
      }
      function g(b2) {
        a && null === b2.alternate && (b2.flags |= 2);
        return b2;
      }
      function h(a2, b2, c2, d2) {
        if (null === b2 || 6 !== b2.tag) return b2 = Qg(c2, a2.mode, d2), b2.return = a2, b2;
        b2 = e(b2, c2);
        b2.return = a2;
        return b2;
      }
      function k(a2, b2, c2, d2) {
        var f2 = c2.type;
        if (f2 === ya) return m(a2, b2, c2.props.children, d2, c2.key);
        if (null !== b2 && (b2.elementType === f2 || "object" === typeof f2 && null !== f2 && f2.$$typeof === Ha && Ng(f2) === b2.type)) return d2 = e(b2, c2.props), d2.ref = Lg(a2, b2, c2), d2.return = a2, d2;
        d2 = Rg(c2.type, c2.key, c2.props, null, a2.mode, d2);
        d2.ref = Lg(a2, b2, c2);
        d2.return = a2;
        return d2;
      }
      function l(a2, b2, c2, d2) {
        if (null === b2 || 4 !== b2.tag || b2.stateNode.containerInfo !== c2.containerInfo || b2.stateNode.implementation !== c2.implementation) return b2 = Sg(c2, a2.mode, d2), b2.return = a2, b2;
        b2 = e(b2, c2.children || []);
        b2.return = a2;
        return b2;
      }
      function m(a2, b2, c2, d2, f2) {
        if (null === b2 || 7 !== b2.tag) return b2 = Tg(c2, a2.mode, d2, f2), b2.return = a2, b2;
        b2 = e(b2, c2);
        b2.return = a2;
        return b2;
      }
      function q(a2, b2, c2) {
        if ("string" === typeof b2 && "" !== b2 || "number" === typeof b2) return b2 = Qg("" + b2, a2.mode, c2), b2.return = a2, b2;
        if ("object" === typeof b2 && null !== b2) {
          switch (b2.$$typeof) {
            case va:
              return c2 = Rg(b2.type, b2.key, b2.props, null, a2.mode, c2), c2.ref = Lg(a2, null, b2), c2.return = a2, c2;
            case wa:
              return b2 = Sg(b2, a2.mode, c2), b2.return = a2, b2;
            case Ha:
              var d2 = b2._init;
              return q(a2, d2(b2._payload), c2);
          }
          if (eb(b2) || Ka(b2)) return b2 = Tg(b2, a2.mode, c2, null), b2.return = a2, b2;
          Mg(a2, b2);
        }
        return null;
      }
      function r(a2, b2, c2, d2) {
        var e2 = null !== b2 ? b2.key : null;
        if ("string" === typeof c2 && "" !== c2 || "number" === typeof c2) return null !== e2 ? null : h(a2, b2, "" + c2, d2);
        if ("object" === typeof c2 && null !== c2) {
          switch (c2.$$typeof) {
            case va:
              return c2.key === e2 ? k(a2, b2, c2, d2) : null;
            case wa:
              return c2.key === e2 ? l(a2, b2, c2, d2) : null;
            case Ha:
              return e2 = c2._init, r(
                a2,
                b2,
                e2(c2._payload),
                d2
              );
          }
          if (eb(c2) || Ka(c2)) return null !== e2 ? null : m(a2, b2, c2, d2, null);
          Mg(a2, c2);
        }
        return null;
      }
      function y(a2, b2, c2, d2, e2) {
        if ("string" === typeof d2 && "" !== d2 || "number" === typeof d2) return a2 = a2.get(c2) || null, h(b2, a2, "" + d2, e2);
        if ("object" === typeof d2 && null !== d2) {
          switch (d2.$$typeof) {
            case va:
              return a2 = a2.get(null === d2.key ? c2 : d2.key) || null, k(b2, a2, d2, e2);
            case wa:
              return a2 = a2.get(null === d2.key ? c2 : d2.key) || null, l(b2, a2, d2, e2);
            case Ha:
              var f2 = d2._init;
              return y(a2, b2, c2, f2(d2._payload), e2);
          }
          if (eb(d2) || Ka(d2)) return a2 = a2.get(c2) || null, m(b2, a2, d2, e2, null);
          Mg(b2, d2);
        }
        return null;
      }
      function n(e2, g2, h2, k2) {
        for (var l2 = null, m2 = null, u = g2, w = g2 = 0, x = null; null !== u && w < h2.length; w++) {
          u.index > w ? (x = u, u = null) : x = u.sibling;
          var n2 = r(e2, u, h2[w], k2);
          if (null === n2) {
            null === u && (u = x);
            break;
          }
          a && u && null === n2.alternate && b(e2, u);
          g2 = f(n2, g2, w);
          null === m2 ? l2 = n2 : m2.sibling = n2;
          m2 = n2;
          u = x;
        }
        if (w === h2.length) return c(e2, u), I && tg(e2, w), l2;
        if (null === u) {
          for (; w < h2.length; w++) u = q(e2, h2[w], k2), null !== u && (g2 = f(u, g2, w), null === m2 ? l2 = u : m2.sibling = u, m2 = u);
          I && tg(e2, w);
          return l2;
        }
        for (u = d(e2, u); w < h2.length; w++) x = y(u, e2, w, h2[w], k2), null !== x && (a && null !== x.alternate && u.delete(null === x.key ? w : x.key), g2 = f(x, g2, w), null === m2 ? l2 = x : m2.sibling = x, m2 = x);
        a && u.forEach(function(a2) {
          return b(e2, a2);
        });
        I && tg(e2, w);
        return l2;
      }
      function t(e2, g2, h2, k2) {
        var l2 = Ka(h2);
        if ("function" !== typeof l2) throw Error(p(150));
        h2 = l2.call(h2);
        if (null == h2) throw Error(p(151));
        for (var u = l2 = null, m2 = g2, w = g2 = 0, x = null, n2 = h2.next(); null !== m2 && !n2.done; w++, n2 = h2.next()) {
          m2.index > w ? (x = m2, m2 = null) : x = m2.sibling;
          var t2 = r(e2, m2, n2.value, k2);
          if (null === t2) {
            null === m2 && (m2 = x);
            break;
          }
          a && m2 && null === t2.alternate && b(e2, m2);
          g2 = f(t2, g2, w);
          null === u ? l2 = t2 : u.sibling = t2;
          u = t2;
          m2 = x;
        }
        if (n2.done) return c(
          e2,
          m2
        ), I && tg(e2, w), l2;
        if (null === m2) {
          for (; !n2.done; w++, n2 = h2.next()) n2 = q(e2, n2.value, k2), null !== n2 && (g2 = f(n2, g2, w), null === u ? l2 = n2 : u.sibling = n2, u = n2);
          I && tg(e2, w);
          return l2;
        }
        for (m2 = d(e2, m2); !n2.done; w++, n2 = h2.next()) n2 = y(m2, e2, w, n2.value, k2), null !== n2 && (a && null !== n2.alternate && m2.delete(null === n2.key ? w : n2.key), g2 = f(n2, g2, w), null === u ? l2 = n2 : u.sibling = n2, u = n2);
        a && m2.forEach(function(a2) {
          return b(e2, a2);
        });
        I && tg(e2, w);
        return l2;
      }
      function J(a2, d2, f2, h2) {
        "object" === typeof f2 && null !== f2 && f2.type === ya && null === f2.key && (f2 = f2.props.children);
        if ("object" === typeof f2 && null !== f2) {
          switch (f2.$$typeof) {
            case va:
              a: {
                for (var k2 = f2.key, l2 = d2; null !== l2; ) {
                  if (l2.key === k2) {
                    k2 = f2.type;
                    if (k2 === ya) {
                      if (7 === l2.tag) {
                        c(a2, l2.sibling);
                        d2 = e(l2, f2.props.children);
                        d2.return = a2;
                        a2 = d2;
                        break a;
                      }
                    } else if (l2.elementType === k2 || "object" === typeof k2 && null !== k2 && k2.$$typeof === Ha && Ng(k2) === l2.type) {
                      c(a2, l2.sibling);
                      d2 = e(l2, f2.props);
                      d2.ref = Lg(a2, l2, f2);
                      d2.return = a2;
                      a2 = d2;
                      break a;
                    }
                    c(a2, l2);
                    break;
                  } else b(a2, l2);
                  l2 = l2.sibling;
                }
                f2.type === ya ? (d2 = Tg(f2.props.children, a2.mode, h2, f2.key), d2.return = a2, a2 = d2) : (h2 = Rg(f2.type, f2.key, f2.props, null, a2.mode, h2), h2.ref = Lg(a2, d2, f2), h2.return = a2, a2 = h2);
              }
              return g(a2);
            case wa:
              a: {
                for (l2 = f2.key; null !== d2; ) {
                  if (d2.key === l2) if (4 === d2.tag && d2.stateNode.containerInfo === f2.containerInfo && d2.stateNode.implementation === f2.implementation) {
                    c(a2, d2.sibling);
                    d2 = e(d2, f2.children || []);
                    d2.return = a2;
                    a2 = d2;
                    break a;
                  } else {
                    c(a2, d2);
                    break;
                  }
                  else b(a2, d2);
                  d2 = d2.sibling;
                }
                d2 = Sg(f2, a2.mode, h2);
                d2.return = a2;
                a2 = d2;
              }
              return g(a2);
            case Ha:
              return l2 = f2._init, J(a2, d2, l2(f2._payload), h2);
          }
          if (eb(f2)) return n(a2, d2, f2, h2);
          if (Ka(f2)) return t(a2, d2, f2, h2);
          Mg(a2, f2);
        }
        return "string" === typeof f2 && "" !== f2 || "number" === typeof f2 ? (f2 = "" + f2, null !== d2 && 6 === d2.tag ? (c(a2, d2.sibling), d2 = e(d2, f2), d2.return = a2, a2 = d2) : (c(a2, d2), d2 = Qg(f2, a2.mode, h2), d2.return = a2, a2 = d2), g(a2)) : c(a2, d2);
      }
      return J;
    }
    var Ug = Og(true), Vg = Og(false), Wg = Uf(null), Xg = null, Yg = null, Zg = null;
    function $g() {
      Zg = Yg = Xg = null;
    }
    function ah(a) {
      var b = Wg.current;
      E(Wg);
      a._currentValue = b;
    }
    function bh(a, b, c) {
      for (; null !== a; ) {
        var d = a.alternate;
        (a.childLanes & b) !== b ? (a.childLanes |= b, null !== d && (d.childLanes |= b)) : null !== d && (d.childLanes & b) !== b && (d.childLanes |= b);
        if (a === c) break;
        a = a.return;
      }
    }
    function ch(a, b) {
      Xg = a;
      Zg = Yg = null;
      a = a.dependencies;
      null !== a && null !== a.firstContext && (0 !== (a.lanes & b) && (dh = true), a.firstContext = null);
    }
    function eh(a) {
      var b = a._currentValue;
      if (Zg !== a) if (a = { context: a, memoizedValue: b, next: null }, null === Yg) {
        if (null === Xg) throw Error(p(308));
        Yg = a;
        Xg.dependencies = { lanes: 0, firstContext: a };
      } else Yg = Yg.next = a;
      return b;
    }
    var fh = null;
    function gh(a) {
      null === fh ? fh = [a] : fh.push(a);
    }
    function hh(a, b, c, d) {
      var e = b.interleaved;
      null === e ? (c.next = c, gh(b)) : (c.next = e.next, e.next = c);
      b.interleaved = c;
      return ih(a, d);
    }
    function ih(a, b) {
      a.lanes |= b;
      var c = a.alternate;
      null !== c && (c.lanes |= b);
      c = a;
      for (a = a.return; null !== a; ) a.childLanes |= b, c = a.alternate, null !== c && (c.childLanes |= b), c = a, a = a.return;
      return 3 === c.tag ? c.stateNode : null;
    }
    var jh = false;
    function kh(a) {
      a.updateQueue = { baseState: a.memoizedState, firstBaseUpdate: null, lastBaseUpdate: null, shared: { pending: null, interleaved: null, lanes: 0 }, effects: null };
    }
    function lh(a, b) {
      a = a.updateQueue;
      b.updateQueue === a && (b.updateQueue = { baseState: a.baseState, firstBaseUpdate: a.firstBaseUpdate, lastBaseUpdate: a.lastBaseUpdate, shared: a.shared, effects: a.effects });
    }
    function mh(a, b) {
      return { eventTime: a, lane: b, tag: 0, payload: null, callback: null, next: null };
    }
    function nh(a, b, c) {
      var d = a.updateQueue;
      if (null === d) return null;
      d = d.shared;
      if (0 !== (K & 2)) {
        var e = d.pending;
        null === e ? b.next = b : (b.next = e.next, e.next = b);
        d.pending = b;
        return ih(a, c);
      }
      e = d.interleaved;
      null === e ? (b.next = b, gh(d)) : (b.next = e.next, e.next = b);
      d.interleaved = b;
      return ih(a, c);
    }
    function oh(a, b, c) {
      b = b.updateQueue;
      if (null !== b && (b = b.shared, 0 !== (c & 4194240))) {
        var d = b.lanes;
        d &= a.pendingLanes;
        c |= d;
        b.lanes = c;
        Cc(a, c);
      }
    }
    function ph(a, b) {
      var c = a.updateQueue, d = a.alternate;
      if (null !== d && (d = d.updateQueue, c === d)) {
        var e = null, f = null;
        c = c.firstBaseUpdate;
        if (null !== c) {
          do {
            var g = { eventTime: c.eventTime, lane: c.lane, tag: c.tag, payload: c.payload, callback: c.callback, next: null };
            null === f ? e = f = g : f = f.next = g;
            c = c.next;
          } while (null !== c);
          null === f ? e = f = b : f = f.next = b;
        } else e = f = b;
        c = { baseState: d.baseState, firstBaseUpdate: e, lastBaseUpdate: f, shared: d.shared, effects: d.effects };
        a.updateQueue = c;
        return;
      }
      a = c.lastBaseUpdate;
      null === a ? c.firstBaseUpdate = b : a.next = b;
      c.lastBaseUpdate = b;
    }
    function qh(a, b, c, d) {
      var e = a.updateQueue;
      jh = false;
      var f = e.firstBaseUpdate, g = e.lastBaseUpdate, h = e.shared.pending;
      if (null !== h) {
        e.shared.pending = null;
        var k = h, l = k.next;
        k.next = null;
        null === g ? f = l : g.next = l;
        g = k;
        var m = a.alternate;
        null !== m && (m = m.updateQueue, h = m.lastBaseUpdate, h !== g && (null === h ? m.firstBaseUpdate = l : h.next = l, m.lastBaseUpdate = k));
      }
      if (null !== f) {
        var q = e.baseState;
        g = 0;
        m = l = k = null;
        h = f;
        do {
          var r = h.lane, y = h.eventTime;
          if ((d & r) === r) {
            null !== m && (m = m.next = {
              eventTime: y,
              lane: 0,
              tag: h.tag,
              payload: h.payload,
              callback: h.callback,
              next: null
            });
            a: {
              var n = a, t = h;
              r = b;
              y = c;
              switch (t.tag) {
                case 1:
                  n = t.payload;
                  if ("function" === typeof n) {
                    q = n.call(y, q, r);
                    break a;
                  }
                  q = n;
                  break a;
                case 3:
                  n.flags = n.flags & -65537 | 128;
                case 0:
                  n = t.payload;
                  r = "function" === typeof n ? n.call(y, q, r) : n;
                  if (null === r || void 0 === r) break a;
                  q = A({}, q, r);
                  break a;
                case 2:
                  jh = true;
              }
            }
            null !== h.callback && 0 !== h.lane && (a.flags |= 64, r = e.effects, null === r ? e.effects = [h] : r.push(h));
          } else y = { eventTime: y, lane: r, tag: h.tag, payload: h.payload, callback: h.callback, next: null }, null === m ? (l = m = y, k = q) : m = m.next = y, g |= r;
          h = h.next;
          if (null === h) if (h = e.shared.pending, null === h) break;
          else r = h, h = r.next, r.next = null, e.lastBaseUpdate = r, e.shared.pending = null;
        } while (1);
        null === m && (k = q);
        e.baseState = k;
        e.firstBaseUpdate = l;
        e.lastBaseUpdate = m;
        b = e.shared.interleaved;
        if (null !== b) {
          e = b;
          do
            g |= e.lane, e = e.next;
          while (e !== b);
        } else null === f && (e.shared.lanes = 0);
        rh |= g;
        a.lanes = g;
        a.memoizedState = q;
      }
    }
    function sh(a, b, c) {
      a = b.effects;
      b.effects = null;
      if (null !== a) for (b = 0; b < a.length; b++) {
        var d = a[b], e = d.callback;
        if (null !== e) {
          d.callback = null;
          d = c;
          if ("function" !== typeof e) throw Error(p(191, e));
          e.call(d);
        }
      }
    }
    var th = {}, uh = Uf(th), vh2 = Uf(th), wh = Uf(th);
    function xh(a) {
      if (a === th) throw Error(p(174));
      return a;
    }
    function yh(a, b) {
      G(wh, b);
      G(vh2, a);
      G(uh, th);
      a = b.nodeType;
      switch (a) {
        case 9:
        case 11:
          b = (b = b.documentElement) ? b.namespaceURI : lb(null, "");
          break;
        default:
          a = 8 === a ? b.parentNode : b, b = a.namespaceURI || null, a = a.tagName, b = lb(b, a);
      }
      E(uh);
      G(uh, b);
    }
    function zh() {
      E(uh);
      E(vh2);
      E(wh);
    }
    function Ah(a) {
      xh(wh.current);
      var b = xh(uh.current);
      var c = lb(b, a.type);
      b !== c && (G(vh2, a), G(uh, c));
    }
    function Bh(a) {
      vh2.current === a && (E(uh), E(vh2));
    }
    var L = Uf(0);
    function Ch(a) {
      for (var b = a; null !== b; ) {
        if (13 === b.tag) {
          var c = b.memoizedState;
          if (null !== c && (c = c.dehydrated, null === c || "$?" === c.data || "$!" === c.data)) return b;
        } else if (19 === b.tag && void 0 !== b.memoizedProps.revealOrder) {
          if (0 !== (b.flags & 128)) return b;
        } else if (null !== b.child) {
          b.child.return = b;
          b = b.child;
          continue;
        }
        if (b === a) break;
        for (; null === b.sibling; ) {
          if (null === b.return || b.return === a) return null;
          b = b.return;
        }
        b.sibling.return = b.return;
        b = b.sibling;
      }
      return null;
    }
    var Dh = [];
    function Eh() {
      for (var a = 0; a < Dh.length; a++) Dh[a]._workInProgressVersionPrimary = null;
      Dh.length = 0;
    }
    var Fh = ua.ReactCurrentDispatcher, Gh = ua.ReactCurrentBatchConfig, Hh = 0, M = null, N = null, O = null, Ih = false, Jh = false, Kh = 0, Lh = 0;
    function P() {
      throw Error(p(321));
    }
    function Mh(a, b) {
      if (null === b) return false;
      for (var c = 0; c < b.length && c < a.length; c++) if (!He(a[c], b[c])) return false;
      return true;
    }
    function Nh(a, b, c, d, e, f) {
      Hh = f;
      M = b;
      b.memoizedState = null;
      b.updateQueue = null;
      b.lanes = 0;
      Fh.current = null === a || null === a.memoizedState ? Oh : Ph;
      a = c(d, e);
      if (Jh) {
        f = 0;
        do {
          Jh = false;
          Kh = 0;
          if (25 <= f) throw Error(p(301));
          f += 1;
          O = N = null;
          b.updateQueue = null;
          Fh.current = Qh;
          a = c(d, e);
        } while (Jh);
      }
      Fh.current = Rh;
      b = null !== N && null !== N.next;
      Hh = 0;
      O = N = M = null;
      Ih = false;
      if (b) throw Error(p(300));
      return a;
    }
    function Sh() {
      var a = 0 !== Kh;
      Kh = 0;
      return a;
    }
    function Th() {
      var a = { memoizedState: null, baseState: null, baseQueue: null, queue: null, next: null };
      null === O ? M.memoizedState = O = a : O = O.next = a;
      return O;
    }
    function Uh() {
      if (null === N) {
        var a = M.alternate;
        a = null !== a ? a.memoizedState : null;
      } else a = N.next;
      var b = null === O ? M.memoizedState : O.next;
      if (null !== b) O = b, N = a;
      else {
        if (null === a) throw Error(p(310));
        N = a;
        a = { memoizedState: N.memoizedState, baseState: N.baseState, baseQueue: N.baseQueue, queue: N.queue, next: null };
        null === O ? M.memoizedState = O = a : O = O.next = a;
      }
      return O;
    }
    function Vh(a, b) {
      return "function" === typeof b ? b(a) : b;
    }
    function Wh(a) {
      var b = Uh(), c = b.queue;
      if (null === c) throw Error(p(311));
      c.lastRenderedReducer = a;
      var d = N, e = d.baseQueue, f = c.pending;
      if (null !== f) {
        if (null !== e) {
          var g = e.next;
          e.next = f.next;
          f.next = g;
        }
        d.baseQueue = e = f;
        c.pending = null;
      }
      if (null !== e) {
        f = e.next;
        d = d.baseState;
        var h = g = null, k = null, l = f;
        do {
          var m = l.lane;
          if ((Hh & m) === m) null !== k && (k = k.next = { lane: 0, action: l.action, hasEagerState: l.hasEagerState, eagerState: l.eagerState, next: null }), d = l.hasEagerState ? l.eagerState : a(d, l.action);
          else {
            var q = {
              lane: m,
              action: l.action,
              hasEagerState: l.hasEagerState,
              eagerState: l.eagerState,
              next: null
            };
            null === k ? (h = k = q, g = d) : k = k.next = q;
            M.lanes |= m;
            rh |= m;
          }
          l = l.next;
        } while (null !== l && l !== f);
        null === k ? g = d : k.next = h;
        He(d, b.memoizedState) || (dh = true);
        b.memoizedState = d;
        b.baseState = g;
        b.baseQueue = k;
        c.lastRenderedState = d;
      }
      a = c.interleaved;
      if (null !== a) {
        e = a;
        do
          f = e.lane, M.lanes |= f, rh |= f, e = e.next;
        while (e !== a);
      } else null === e && (c.lanes = 0);
      return [b.memoizedState, c.dispatch];
    }
    function Xh(a) {
      var b = Uh(), c = b.queue;
      if (null === c) throw Error(p(311));
      c.lastRenderedReducer = a;
      var d = c.dispatch, e = c.pending, f = b.memoizedState;
      if (null !== e) {
        c.pending = null;
        var g = e = e.next;
        do
          f = a(f, g.action), g = g.next;
        while (g !== e);
        He(f, b.memoizedState) || (dh = true);
        b.memoizedState = f;
        null === b.baseQueue && (b.baseState = f);
        c.lastRenderedState = f;
      }
      return [f, d];
    }
    function Yh() {
    }
    function Zh(a, b) {
      var c = M, d = Uh(), e = b(), f = !He(d.memoizedState, e);
      f && (d.memoizedState = e, dh = true);
      d = d.queue;
      $h(ai.bind(null, c, d, a), [a]);
      if (d.getSnapshot !== b || f || null !== O && O.memoizedState.tag & 1) {
        c.flags |= 2048;
        bi(9, ci.bind(null, c, d, e, b), void 0, null);
        if (null === Q) throw Error(p(349));
        0 !== (Hh & 30) || di(c, b, e);
      }
      return e;
    }
    function di(a, b, c) {
      a.flags |= 16384;
      a = { getSnapshot: b, value: c };
      b = M.updateQueue;
      null === b ? (b = { lastEffect: null, stores: null }, M.updateQueue = b, b.stores = [a]) : (c = b.stores, null === c ? b.stores = [a] : c.push(a));
    }
    function ci(a, b, c, d) {
      b.value = c;
      b.getSnapshot = d;
      ei(b) && fi(a);
    }
    function ai(a, b, c) {
      return c(function() {
        ei(b) && fi(a);
      });
    }
    function ei(a) {
      var b = a.getSnapshot;
      a = a.value;
      try {
        var c = b();
        return !He(a, c);
      } catch (d) {
        return true;
      }
    }
    function fi(a) {
      var b = ih(a, 1);
      null !== b && gi(b, a, 1, -1);
    }
    function hi(a) {
      var b = Th();
      "function" === typeof a && (a = a());
      b.memoizedState = b.baseState = a;
      a = { pending: null, interleaved: null, lanes: 0, dispatch: null, lastRenderedReducer: Vh, lastRenderedState: a };
      b.queue = a;
      a = a.dispatch = ii.bind(null, M, a);
      return [b.memoizedState, a];
    }
    function bi(a, b, c, d) {
      a = { tag: a, create: b, destroy: c, deps: d, next: null };
      b = M.updateQueue;
      null === b ? (b = { lastEffect: null, stores: null }, M.updateQueue = b, b.lastEffect = a.next = a) : (c = b.lastEffect, null === c ? b.lastEffect = a.next = a : (d = c.next, c.next = a, a.next = d, b.lastEffect = a));
      return a;
    }
    function ji() {
      return Uh().memoizedState;
    }
    function ki(a, b, c, d) {
      var e = Th();
      M.flags |= a;
      e.memoizedState = bi(1 | b, c, void 0, void 0 === d ? null : d);
    }
    function li(a, b, c, d) {
      var e = Uh();
      d = void 0 === d ? null : d;
      var f = void 0;
      if (null !== N) {
        var g = N.memoizedState;
        f = g.destroy;
        if (null !== d && Mh(d, g.deps)) {
          e.memoizedState = bi(b, c, f, d);
          return;
        }
      }
      M.flags |= a;
      e.memoizedState = bi(1 | b, c, f, d);
    }
    function mi(a, b) {
      return ki(8390656, 8, a, b);
    }
    function $h(a, b) {
      return li(2048, 8, a, b);
    }
    function ni(a, b) {
      return li(4, 2, a, b);
    }
    function oi(a, b) {
      return li(4, 4, a, b);
    }
    function pi(a, b) {
      if ("function" === typeof b) return a = a(), b(a), function() {
        b(null);
      };
      if (null !== b && void 0 !== b) return a = a(), b.current = a, function() {
        b.current = null;
      };
    }
    function qi(a, b, c) {
      c = null !== c && void 0 !== c ? c.concat([a]) : null;
      return li(4, 4, pi.bind(null, b, a), c);
    }
    function ri() {
    }
    function si(a, b) {
      var c = Uh();
      b = void 0 === b ? null : b;
      var d = c.memoizedState;
      if (null !== d && null !== b && Mh(b, d[1])) return d[0];
      c.memoizedState = [a, b];
      return a;
    }
    function ti(a, b) {
      var c = Uh();
      b = void 0 === b ? null : b;
      var d = c.memoizedState;
      if (null !== d && null !== b && Mh(b, d[1])) return d[0];
      a = a();
      c.memoizedState = [a, b];
      return a;
    }
    function ui(a, b, c) {
      if (0 === (Hh & 21)) return a.baseState && (a.baseState = false, dh = true), a.memoizedState = c;
      He(c, b) || (c = yc(), M.lanes |= c, rh |= c, a.baseState = true);
      return b;
    }
    function vi(a, b) {
      var c = C;
      C = 0 !== c && 4 > c ? c : 4;
      a(true);
      var d = Gh.transition;
      Gh.transition = {};
      try {
        a(false), b();
      } finally {
        C = c, Gh.transition = d;
      }
    }
    function wi() {
      return Uh().memoizedState;
    }
    function xi(a, b, c) {
      var d = yi(a);
      c = { lane: d, action: c, hasEagerState: false, eagerState: null, next: null };
      if (zi(a)) Ai(b, c);
      else if (c = hh(a, b, c, d), null !== c) {
        var e = R();
        gi(c, a, d, e);
        Bi(c, b, d);
      }
    }
    function ii(a, b, c) {
      var d = yi(a), e = { lane: d, action: c, hasEagerState: false, eagerState: null, next: null };
      if (zi(a)) Ai(b, e);
      else {
        var f = a.alternate;
        if (0 === a.lanes && (null === f || 0 === f.lanes) && (f = b.lastRenderedReducer, null !== f)) try {
          var g = b.lastRenderedState, h = f(g, c);
          e.hasEagerState = true;
          e.eagerState = h;
          if (He(h, g)) {
            var k = b.interleaved;
            null === k ? (e.next = e, gh(b)) : (e.next = k.next, k.next = e);
            b.interleaved = e;
            return;
          }
        } catch (l) {
        } finally {
        }
        c = hh(a, b, e, d);
        null !== c && (e = R(), gi(c, a, d, e), Bi(c, b, d));
      }
    }
    function zi(a) {
      var b = a.alternate;
      return a === M || null !== b && b === M;
    }
    function Ai(a, b) {
      Jh = Ih = true;
      var c = a.pending;
      null === c ? b.next = b : (b.next = c.next, c.next = b);
      a.pending = b;
    }
    function Bi(a, b, c) {
      if (0 !== (c & 4194240)) {
        var d = b.lanes;
        d &= a.pendingLanes;
        c |= d;
        b.lanes = c;
        Cc(a, c);
      }
    }
    var Rh = { readContext: eh, useCallback: P, useContext: P, useEffect: P, useImperativeHandle: P, useInsertionEffect: P, useLayoutEffect: P, useMemo: P, useReducer: P, useRef: P, useState: P, useDebugValue: P, useDeferredValue: P, useTransition: P, useMutableSource: P, useSyncExternalStore: P, useId: P, unstable_isNewReconciler: false }, Oh = { readContext: eh, useCallback: function(a, b) {
      Th().memoizedState = [a, void 0 === b ? null : b];
      return a;
    }, useContext: eh, useEffect: mi, useImperativeHandle: function(a, b, c) {
      c = null !== c && void 0 !== c ? c.concat([a]) : null;
      return ki(
        4194308,
        4,
        pi.bind(null, b, a),
        c
      );
    }, useLayoutEffect: function(a, b) {
      return ki(4194308, 4, a, b);
    }, useInsertionEffect: function(a, b) {
      return ki(4, 2, a, b);
    }, useMemo: function(a, b) {
      var c = Th();
      b = void 0 === b ? null : b;
      a = a();
      c.memoizedState = [a, b];
      return a;
    }, useReducer: function(a, b, c) {
      var d = Th();
      b = void 0 !== c ? c(b) : b;
      d.memoizedState = d.baseState = b;
      a = { pending: null, interleaved: null, lanes: 0, dispatch: null, lastRenderedReducer: a, lastRenderedState: b };
      d.queue = a;
      a = a.dispatch = xi.bind(null, M, a);
      return [d.memoizedState, a];
    }, useRef: function(a) {
      var b = Th();
      a = { current: a };
      return b.memoizedState = a;
    }, useState: hi, useDebugValue: ri, useDeferredValue: function(a) {
      return Th().memoizedState = a;
    }, useTransition: function() {
      var a = hi(false), b = a[0];
      a = vi.bind(null, a[1]);
      Th().memoizedState = a;
      return [b, a];
    }, useMutableSource: function() {
    }, useSyncExternalStore: function(a, b, c) {
      var d = M, e = Th();
      if (I) {
        if (void 0 === c) throw Error(p(407));
        c = c();
      } else {
        c = b();
        if (null === Q) throw Error(p(349));
        0 !== (Hh & 30) || di(d, b, c);
      }
      e.memoizedState = c;
      var f = { value: c, getSnapshot: b };
      e.queue = f;
      mi(ai.bind(
        null,
        d,
        f,
        a
      ), [a]);
      d.flags |= 2048;
      bi(9, ci.bind(null, d, f, c, b), void 0, null);
      return c;
    }, useId: function() {
      var a = Th(), b = Q.identifierPrefix;
      if (I) {
        var c = sg;
        var d = rg;
        c = (d & ~(1 << 32 - oc(d) - 1)).toString(32) + c;
        b = ":" + b + "R" + c;
        c = Kh++;
        0 < c && (b += "H" + c.toString(32));
        b += ":";
      } else c = Lh++, b = ":" + b + "r" + c.toString(32) + ":";
      return a.memoizedState = b;
    }, unstable_isNewReconciler: false }, Ph = {
      readContext: eh,
      useCallback: si,
      useContext: eh,
      useEffect: $h,
      useImperativeHandle: qi,
      useInsertionEffect: ni,
      useLayoutEffect: oi,
      useMemo: ti,
      useReducer: Wh,
      useRef: ji,
      useState: function() {
        return Wh(Vh);
      },
      useDebugValue: ri,
      useDeferredValue: function(a) {
        var b = Uh();
        return ui(b, N.memoizedState, a);
      },
      useTransition: function() {
        var a = Wh(Vh)[0], b = Uh().memoizedState;
        return [a, b];
      },
      useMutableSource: Yh,
      useSyncExternalStore: Zh,
      useId: wi,
      unstable_isNewReconciler: false
    }, Qh = { readContext: eh, useCallback: si, useContext: eh, useEffect: $h, useImperativeHandle: qi, useInsertionEffect: ni, useLayoutEffect: oi, useMemo: ti, useReducer: Xh, useRef: ji, useState: function() {
      return Xh(Vh);
    }, useDebugValue: ri, useDeferredValue: function(a) {
      var b = Uh();
      return null === N ? b.memoizedState = a : ui(b, N.memoizedState, a);
    }, useTransition: function() {
      var a = Xh(Vh)[0], b = Uh().memoizedState;
      return [a, b];
    }, useMutableSource: Yh, useSyncExternalStore: Zh, useId: wi, unstable_isNewReconciler: false };
    function Ci(a, b) {
      if (a && a.defaultProps) {
        b = A({}, b);
        a = a.defaultProps;
        for (var c in a) void 0 === b[c] && (b[c] = a[c]);
        return b;
      }
      return b;
    }
    function Di(a, b, c, d) {
      b = a.memoizedState;
      c = c(d, b);
      c = null === c || void 0 === c ? b : A({}, b, c);
      a.memoizedState = c;
      0 === a.lanes && (a.updateQueue.baseState = c);
    }
    var Ei = { isMounted: function(a) {
      return (a = a._reactInternals) ? Vb(a) === a : false;
    }, enqueueSetState: function(a, b, c) {
      a = a._reactInternals;
      var d = R(), e = yi(a), f = mh(d, e);
      f.payload = b;
      void 0 !== c && null !== c && (f.callback = c);
      b = nh(a, f, e);
      null !== b && (gi(b, a, e, d), oh(b, a, e));
    }, enqueueReplaceState: function(a, b, c) {
      a = a._reactInternals;
      var d = R(), e = yi(a), f = mh(d, e);
      f.tag = 1;
      f.payload = b;
      void 0 !== c && null !== c && (f.callback = c);
      b = nh(a, f, e);
      null !== b && (gi(b, a, e, d), oh(b, a, e));
    }, enqueueForceUpdate: function(a, b) {
      a = a._reactInternals;
      var c = R(), d = yi(a), e = mh(c, d);
      e.tag = 2;
      void 0 !== b && null !== b && (e.callback = b);
      b = nh(a, e, d);
      null !== b && (gi(b, a, d, c), oh(b, a, d));
    } };
    function Fi(a, b, c, d, e, f, g) {
      a = a.stateNode;
      return "function" === typeof a.shouldComponentUpdate ? a.shouldComponentUpdate(d, f, g) : b.prototype && b.prototype.isPureReactComponent ? !Ie(c, d) || !Ie(e, f) : true;
    }
    function Gi(a, b, c) {
      var d = false, e = Vf;
      var f = b.contextType;
      "object" === typeof f && null !== f ? f = eh(f) : (e = Zf(b) ? Xf : H.current, d = b.contextTypes, f = (d = null !== d && void 0 !== d) ? Yf(a, e) : Vf);
      b = new b(c, f);
      a.memoizedState = null !== b.state && void 0 !== b.state ? b.state : null;
      b.updater = Ei;
      a.stateNode = b;
      b._reactInternals = a;
      d && (a = a.stateNode, a.__reactInternalMemoizedUnmaskedChildContext = e, a.__reactInternalMemoizedMaskedChildContext = f);
      return b;
    }
    function Hi(a, b, c, d) {
      a = b.state;
      "function" === typeof b.componentWillReceiveProps && b.componentWillReceiveProps(c, d);
      "function" === typeof b.UNSAFE_componentWillReceiveProps && b.UNSAFE_componentWillReceiveProps(c, d);
      b.state !== a && Ei.enqueueReplaceState(b, b.state, null);
    }
    function Ii(a, b, c, d) {
      var e = a.stateNode;
      e.props = c;
      e.state = a.memoizedState;
      e.refs = {};
      kh(a);
      var f = b.contextType;
      "object" === typeof f && null !== f ? e.context = eh(f) : (f = Zf(b) ? Xf : H.current, e.context = Yf(a, f));
      e.state = a.memoizedState;
      f = b.getDerivedStateFromProps;
      "function" === typeof f && (Di(a, b, f, c), e.state = a.memoizedState);
      "function" === typeof b.getDerivedStateFromProps || "function" === typeof e.getSnapshotBeforeUpdate || "function" !== typeof e.UNSAFE_componentWillMount && "function" !== typeof e.componentWillMount || (b = e.state, "function" === typeof e.componentWillMount && e.componentWillMount(), "function" === typeof e.UNSAFE_componentWillMount && e.UNSAFE_componentWillMount(), b !== e.state && Ei.enqueueReplaceState(e, e.state, null), qh(a, c, e, d), e.state = a.memoizedState);
      "function" === typeof e.componentDidMount && (a.flags |= 4194308);
    }
    function Ji(a, b) {
      try {
        var c = "", d = b;
        do
          c += Pa(d), d = d.return;
        while (d);
        var e = c;
      } catch (f) {
        e = "\nError generating stack: " + f.message + "\n" + f.stack;
      }
      return { value: a, source: b, stack: e, digest: null };
    }
    function Ki(a, b, c) {
      return { value: a, source: null, stack: null != c ? c : null, digest: null != b ? b : null };
    }
    function Li(a, b) {
      try {
        console.error(b.value);
      } catch (c) {
        setTimeout(function() {
          throw c;
        });
      }
    }
    var Mi = "function" === typeof WeakMap ? WeakMap : Map;
    function Ni(a, b, c) {
      c = mh(-1, c);
      c.tag = 3;
      c.payload = { element: null };
      var d = b.value;
      c.callback = function() {
        Oi || (Oi = true, Pi = d);
        Li(a, b);
      };
      return c;
    }
    function Qi(a, b, c) {
      c = mh(-1, c);
      c.tag = 3;
      var d = a.type.getDerivedStateFromError;
      if ("function" === typeof d) {
        var e = b.value;
        c.payload = function() {
          return d(e);
        };
        c.callback = function() {
          Li(a, b);
        };
      }
      var f = a.stateNode;
      null !== f && "function" === typeof f.componentDidCatch && (c.callback = function() {
        Li(a, b);
        "function" !== typeof d && (null === Ri ? Ri = /* @__PURE__ */ new Set([this]) : Ri.add(this));
        var c2 = b.stack;
        this.componentDidCatch(b.value, { componentStack: null !== c2 ? c2 : "" });
      });
      return c;
    }
    function Si(a, b, c) {
      var d = a.pingCache;
      if (null === d) {
        d = a.pingCache = new Mi();
        var e = /* @__PURE__ */ new Set();
        d.set(b, e);
      } else e = d.get(b), void 0 === e && (e = /* @__PURE__ */ new Set(), d.set(b, e));
      e.has(c) || (e.add(c), a = Ti.bind(null, a, b, c), b.then(a, a));
    }
    function Ui(a) {
      do {
        var b;
        if (b = 13 === a.tag) b = a.memoizedState, b = null !== b ? null !== b.dehydrated ? true : false : true;
        if (b) return a;
        a = a.return;
      } while (null !== a);
      return null;
    }
    function Vi(a, b, c, d, e) {
      if (0 === (a.mode & 1)) return a === b ? a.flags |= 65536 : (a.flags |= 128, c.flags |= 131072, c.flags &= -52805, 1 === c.tag && (null === c.alternate ? c.tag = 17 : (b = mh(-1, 1), b.tag = 2, nh(c, b, 1))), c.lanes |= 1), a;
      a.flags |= 65536;
      a.lanes = e;
      return a;
    }
    var Wi = ua.ReactCurrentOwner, dh = false;
    function Xi(a, b, c, d) {
      b.child = null === a ? Vg(b, null, c, d) : Ug(b, a.child, c, d);
    }
    function Yi(a, b, c, d, e) {
      c = c.render;
      var f = b.ref;
      ch(b, e);
      d = Nh(a, b, c, d, f, e);
      c = Sh();
      if (null !== a && !dh) return b.updateQueue = a.updateQueue, b.flags &= -2053, a.lanes &= ~e, Zi(a, b, e);
      I && c && vg(b);
      b.flags |= 1;
      Xi(a, b, d, e);
      return b.child;
    }
    function $i(a, b, c, d, e) {
      if (null === a) {
        var f = c.type;
        if ("function" === typeof f && !aj(f) && void 0 === f.defaultProps && null === c.compare && void 0 === c.defaultProps) return b.tag = 15, b.type = f, bj(a, b, f, d, e);
        a = Rg(c.type, null, d, b, b.mode, e);
        a.ref = b.ref;
        a.return = b;
        return b.child = a;
      }
      f = a.child;
      if (0 === (a.lanes & e)) {
        var g = f.memoizedProps;
        c = c.compare;
        c = null !== c ? c : Ie;
        if (c(g, d) && a.ref === b.ref) return Zi(a, b, e);
      }
      b.flags |= 1;
      a = Pg(f, d);
      a.ref = b.ref;
      a.return = b;
      return b.child = a;
    }
    function bj(a, b, c, d, e) {
      if (null !== a) {
        var f = a.memoizedProps;
        if (Ie(f, d) && a.ref === b.ref) if (dh = false, b.pendingProps = d = f, 0 !== (a.lanes & e)) 0 !== (a.flags & 131072) && (dh = true);
        else return b.lanes = a.lanes, Zi(a, b, e);
      }
      return cj(a, b, c, d, e);
    }
    function dj(a, b, c) {
      var d = b.pendingProps, e = d.children, f = null !== a ? a.memoizedState : null;
      if ("hidden" === d.mode) if (0 === (b.mode & 1)) b.memoizedState = { baseLanes: 0, cachePool: null, transitions: null }, G(ej, fj), fj |= c;
      else {
        if (0 === (c & 1073741824)) return a = null !== f ? f.baseLanes | c : c, b.lanes = b.childLanes = 1073741824, b.memoizedState = { baseLanes: a, cachePool: null, transitions: null }, b.updateQueue = null, G(ej, fj), fj |= a, null;
        b.memoizedState = { baseLanes: 0, cachePool: null, transitions: null };
        d = null !== f ? f.baseLanes : c;
        G(ej, fj);
        fj |= d;
      }
      else null !== f ? (d = f.baseLanes | c, b.memoizedState = null) : d = c, G(ej, fj), fj |= d;
      Xi(a, b, e, c);
      return b.child;
    }
    function gj(a, b) {
      var c = b.ref;
      if (null === a && null !== c || null !== a && a.ref !== c) b.flags |= 512, b.flags |= 2097152;
    }
    function cj(a, b, c, d, e) {
      var f = Zf(c) ? Xf : H.current;
      f = Yf(b, f);
      ch(b, e);
      c = Nh(a, b, c, d, f, e);
      d = Sh();
      if (null !== a && !dh) return b.updateQueue = a.updateQueue, b.flags &= -2053, a.lanes &= ~e, Zi(a, b, e);
      I && d && vg(b);
      b.flags |= 1;
      Xi(a, b, c, e);
      return b.child;
    }
    function hj(a, b, c, d, e) {
      if (Zf(c)) {
        var f = true;
        cg(b);
      } else f = false;
      ch(b, e);
      if (null === b.stateNode) ij(a, b), Gi(b, c, d), Ii(b, c, d, e), d = true;
      else if (null === a) {
        var g = b.stateNode, h = b.memoizedProps;
        g.props = h;
        var k = g.context, l = c.contextType;
        "object" === typeof l && null !== l ? l = eh(l) : (l = Zf(c) ? Xf : H.current, l = Yf(b, l));
        var m = c.getDerivedStateFromProps, q = "function" === typeof m || "function" === typeof g.getSnapshotBeforeUpdate;
        q || "function" !== typeof g.UNSAFE_componentWillReceiveProps && "function" !== typeof g.componentWillReceiveProps || (h !== d || k !== l) && Hi(b, g, d, l);
        jh = false;
        var r = b.memoizedState;
        g.state = r;
        qh(b, d, g, e);
        k = b.memoizedState;
        h !== d || r !== k || Wf.current || jh ? ("function" === typeof m && (Di(b, c, m, d), k = b.memoizedState), (h = jh || Fi(b, c, h, d, r, k, l)) ? (q || "function" !== typeof g.UNSAFE_componentWillMount && "function" !== typeof g.componentWillMount || ("function" === typeof g.componentWillMount && g.componentWillMount(), "function" === typeof g.UNSAFE_componentWillMount && g.UNSAFE_componentWillMount()), "function" === typeof g.componentDidMount && (b.flags |= 4194308)) : ("function" === typeof g.componentDidMount && (b.flags |= 4194308), b.memoizedProps = d, b.memoizedState = k), g.props = d, g.state = k, g.context = l, d = h) : ("function" === typeof g.componentDidMount && (b.flags |= 4194308), d = false);
      } else {
        g = b.stateNode;
        lh(a, b);
        h = b.memoizedProps;
        l = b.type === b.elementType ? h : Ci(b.type, h);
        g.props = l;
        q = b.pendingProps;
        r = g.context;
        k = c.contextType;
        "object" === typeof k && null !== k ? k = eh(k) : (k = Zf(c) ? Xf : H.current, k = Yf(b, k));
        var y = c.getDerivedStateFromProps;
        (m = "function" === typeof y || "function" === typeof g.getSnapshotBeforeUpdate) || "function" !== typeof g.UNSAFE_componentWillReceiveProps && "function" !== typeof g.componentWillReceiveProps || (h !== q || r !== k) && Hi(b, g, d, k);
        jh = false;
        r = b.memoizedState;
        g.state = r;
        qh(b, d, g, e);
        var n = b.memoizedState;
        h !== q || r !== n || Wf.current || jh ? ("function" === typeof y && (Di(b, c, y, d), n = b.memoizedState), (l = jh || Fi(b, c, l, d, r, n, k) || false) ? (m || "function" !== typeof g.UNSAFE_componentWillUpdate && "function" !== typeof g.componentWillUpdate || ("function" === typeof g.componentWillUpdate && g.componentWillUpdate(d, n, k), "function" === typeof g.UNSAFE_componentWillUpdate && g.UNSAFE_componentWillUpdate(d, n, k)), "function" === typeof g.componentDidUpdate && (b.flags |= 4), "function" === typeof g.getSnapshotBeforeUpdate && (b.flags |= 1024)) : ("function" !== typeof g.componentDidUpdate || h === a.memoizedProps && r === a.memoizedState || (b.flags |= 4), "function" !== typeof g.getSnapshotBeforeUpdate || h === a.memoizedProps && r === a.memoizedState || (b.flags |= 1024), b.memoizedProps = d, b.memoizedState = n), g.props = d, g.state = n, g.context = k, d = l) : ("function" !== typeof g.componentDidUpdate || h === a.memoizedProps && r === a.memoizedState || (b.flags |= 4), "function" !== typeof g.getSnapshotBeforeUpdate || h === a.memoizedProps && r === a.memoizedState || (b.flags |= 1024), d = false);
      }
      return jj(a, b, c, d, f, e);
    }
    function jj(a, b, c, d, e, f) {
      gj(a, b);
      var g = 0 !== (b.flags & 128);
      if (!d && !g) return e && dg(b, c, false), Zi(a, b, f);
      d = b.stateNode;
      Wi.current = b;
      var h = g && "function" !== typeof c.getDerivedStateFromError ? null : d.render();
      b.flags |= 1;
      null !== a && g ? (b.child = Ug(b, a.child, null, f), b.child = Ug(b, null, h, f)) : Xi(a, b, h, f);
      b.memoizedState = d.state;
      e && dg(b, c, true);
      return b.child;
    }
    function kj(a) {
      var b = a.stateNode;
      b.pendingContext ? ag(a, b.pendingContext, b.pendingContext !== b.context) : b.context && ag(a, b.context, false);
      yh(a, b.containerInfo);
    }
    function lj(a, b, c, d, e) {
      Ig();
      Jg(e);
      b.flags |= 256;
      Xi(a, b, c, d);
      return b.child;
    }
    var mj = { dehydrated: null, treeContext: null, retryLane: 0 };
    function nj(a) {
      return { baseLanes: a, cachePool: null, transitions: null };
    }
    function oj(a, b, c) {
      var d = b.pendingProps, e = L.current, f = false, g = 0 !== (b.flags & 128), h;
      (h = g) || (h = null !== a && null === a.memoizedState ? false : 0 !== (e & 2));
      if (h) f = true, b.flags &= -129;
      else if (null === a || null !== a.memoizedState) e |= 1;
      G(L, e & 1);
      if (null === a) {
        Eg(b);
        a = b.memoizedState;
        if (null !== a && (a = a.dehydrated, null !== a)) return 0 === (b.mode & 1) ? b.lanes = 1 : "$!" === a.data ? b.lanes = 8 : b.lanes = 1073741824, null;
        g = d.children;
        a = d.fallback;
        return f ? (d = b.mode, f = b.child, g = { mode: "hidden", children: g }, 0 === (d & 1) && null !== f ? (f.childLanes = 0, f.pendingProps = g) : f = pj(g, d, 0, null), a = Tg(a, d, c, null), f.return = b, a.return = b, f.sibling = a, b.child = f, b.child.memoizedState = nj(c), b.memoizedState = mj, a) : qj(b, g);
      }
      e = a.memoizedState;
      if (null !== e && (h = e.dehydrated, null !== h)) return rj(a, b, g, d, h, e, c);
      if (f) {
        f = d.fallback;
        g = b.mode;
        e = a.child;
        h = e.sibling;
        var k = { mode: "hidden", children: d.children };
        0 === (g & 1) && b.child !== e ? (d = b.child, d.childLanes = 0, d.pendingProps = k, b.deletions = null) : (d = Pg(e, k), d.subtreeFlags = e.subtreeFlags & 14680064);
        null !== h ? f = Pg(h, f) : (f = Tg(f, g, c, null), f.flags |= 2);
        f.return = b;
        d.return = b;
        d.sibling = f;
        b.child = d;
        d = f;
        f = b.child;
        g = a.child.memoizedState;
        g = null === g ? nj(c) : { baseLanes: g.baseLanes | c, cachePool: null, transitions: g.transitions };
        f.memoizedState = g;
        f.childLanes = a.childLanes & ~c;
        b.memoizedState = mj;
        return d;
      }
      f = a.child;
      a = f.sibling;
      d = Pg(f, { mode: "visible", children: d.children });
      0 === (b.mode & 1) && (d.lanes = c);
      d.return = b;
      d.sibling = null;
      null !== a && (c = b.deletions, null === c ? (b.deletions = [a], b.flags |= 16) : c.push(a));
      b.child = d;
      b.memoizedState = null;
      return d;
    }
    function qj(a, b) {
      b = pj({ mode: "visible", children: b }, a.mode, 0, null);
      b.return = a;
      return a.child = b;
    }
    function sj(a, b, c, d) {
      null !== d && Jg(d);
      Ug(b, a.child, null, c);
      a = qj(b, b.pendingProps.children);
      a.flags |= 2;
      b.memoizedState = null;
      return a;
    }
    function rj(a, b, c, d, e, f, g) {
      if (c) {
        if (b.flags & 256) return b.flags &= -257, d = Ki(Error(p(422))), sj(a, b, g, d);
        if (null !== b.memoizedState) return b.child = a.child, b.flags |= 128, null;
        f = d.fallback;
        e = b.mode;
        d = pj({ mode: "visible", children: d.children }, e, 0, null);
        f = Tg(f, e, g, null);
        f.flags |= 2;
        d.return = b;
        f.return = b;
        d.sibling = f;
        b.child = d;
        0 !== (b.mode & 1) && Ug(b, a.child, null, g);
        b.child.memoizedState = nj(g);
        b.memoizedState = mj;
        return f;
      }
      if (0 === (b.mode & 1)) return sj(a, b, g, null);
      if ("$!" === e.data) {
        d = e.nextSibling && e.nextSibling.dataset;
        if (d) var h = d.dgst;
        d = h;
        f = Error(p(419));
        d = Ki(f, d, void 0);
        return sj(a, b, g, d);
      }
      h = 0 !== (g & a.childLanes);
      if (dh || h) {
        d = Q;
        if (null !== d) {
          switch (g & -g) {
            case 4:
              e = 2;
              break;
            case 16:
              e = 8;
              break;
            case 64:
            case 128:
            case 256:
            case 512:
            case 1024:
            case 2048:
            case 4096:
            case 8192:
            case 16384:
            case 32768:
            case 65536:
            case 131072:
            case 262144:
            case 524288:
            case 1048576:
            case 2097152:
            case 4194304:
            case 8388608:
            case 16777216:
            case 33554432:
            case 67108864:
              e = 32;
              break;
            case 536870912:
              e = 268435456;
              break;
            default:
              e = 0;
          }
          e = 0 !== (e & (d.suspendedLanes | g)) ? 0 : e;
          0 !== e && e !== f.retryLane && (f.retryLane = e, ih(a, e), gi(d, a, e, -1));
        }
        tj();
        d = Ki(Error(p(421)));
        return sj(a, b, g, d);
      }
      if ("$?" === e.data) return b.flags |= 128, b.child = a.child, b = uj.bind(null, a), e._reactRetry = b, null;
      a = f.treeContext;
      yg = Lf(e.nextSibling);
      xg = b;
      I = true;
      zg = null;
      null !== a && (og[pg++] = rg, og[pg++] = sg, og[pg++] = qg, rg = a.id, sg = a.overflow, qg = b);
      b = qj(b, d.children);
      b.flags |= 4096;
      return b;
    }
    function vj(a, b, c) {
      a.lanes |= b;
      var d = a.alternate;
      null !== d && (d.lanes |= b);
      bh(a.return, b, c);
    }
    function wj(a, b, c, d, e) {
      var f = a.memoizedState;
      null === f ? a.memoizedState = { isBackwards: b, rendering: null, renderingStartTime: 0, last: d, tail: c, tailMode: e } : (f.isBackwards = b, f.rendering = null, f.renderingStartTime = 0, f.last = d, f.tail = c, f.tailMode = e);
    }
    function xj(a, b, c) {
      var d = b.pendingProps, e = d.revealOrder, f = d.tail;
      Xi(a, b, d.children, c);
      d = L.current;
      if (0 !== (d & 2)) d = d & 1 | 2, b.flags |= 128;
      else {
        if (null !== a && 0 !== (a.flags & 128)) a: for (a = b.child; null !== a; ) {
          if (13 === a.tag) null !== a.memoizedState && vj(a, c, b);
          else if (19 === a.tag) vj(a, c, b);
          else if (null !== a.child) {
            a.child.return = a;
            a = a.child;
            continue;
          }
          if (a === b) break a;
          for (; null === a.sibling; ) {
            if (null === a.return || a.return === b) break a;
            a = a.return;
          }
          a.sibling.return = a.return;
          a = a.sibling;
        }
        d &= 1;
      }
      G(L, d);
      if (0 === (b.mode & 1)) b.memoizedState = null;
      else switch (e) {
        case "forwards":
          c = b.child;
          for (e = null; null !== c; ) a = c.alternate, null !== a && null === Ch(a) && (e = c), c = c.sibling;
          c = e;
          null === c ? (e = b.child, b.child = null) : (e = c.sibling, c.sibling = null);
          wj(b, false, e, c, f);
          break;
        case "backwards":
          c = null;
          e = b.child;
          for (b.child = null; null !== e; ) {
            a = e.alternate;
            if (null !== a && null === Ch(a)) {
              b.child = e;
              break;
            }
            a = e.sibling;
            e.sibling = c;
            c = e;
            e = a;
          }
          wj(b, true, c, null, f);
          break;
        case "together":
          wj(b, false, null, null, void 0);
          break;
        default:
          b.memoizedState = null;
      }
      return b.child;
    }
    function ij(a, b) {
      0 === (b.mode & 1) && null !== a && (a.alternate = null, b.alternate = null, b.flags |= 2);
    }
    function Zi(a, b, c) {
      null !== a && (b.dependencies = a.dependencies);
      rh |= b.lanes;
      if (0 === (c & b.childLanes)) return null;
      if (null !== a && b.child !== a.child) throw Error(p(153));
      if (null !== b.child) {
        a = b.child;
        c = Pg(a, a.pendingProps);
        b.child = c;
        for (c.return = b; null !== a.sibling; ) a = a.sibling, c = c.sibling = Pg(a, a.pendingProps), c.return = b;
        c.sibling = null;
      }
      return b.child;
    }
    function yj(a, b, c) {
      switch (b.tag) {
        case 3:
          kj(b);
          Ig();
          break;
        case 5:
          Ah(b);
          break;
        case 1:
          Zf(b.type) && cg(b);
          break;
        case 4:
          yh(b, b.stateNode.containerInfo);
          break;
        case 10:
          var d = b.type._context, e = b.memoizedProps.value;
          G(Wg, d._currentValue);
          d._currentValue = e;
          break;
        case 13:
          d = b.memoizedState;
          if (null !== d) {
            if (null !== d.dehydrated) return G(L, L.current & 1), b.flags |= 128, null;
            if (0 !== (c & b.child.childLanes)) return oj(a, b, c);
            G(L, L.current & 1);
            a = Zi(a, b, c);
            return null !== a ? a.sibling : null;
          }
          G(L, L.current & 1);
          break;
        case 19:
          d = 0 !== (c & b.childLanes);
          if (0 !== (a.flags & 128)) {
            if (d) return xj(a, b, c);
            b.flags |= 128;
          }
          e = b.memoizedState;
          null !== e && (e.rendering = null, e.tail = null, e.lastEffect = null);
          G(L, L.current);
          if (d) break;
          else return null;
        case 22:
        case 23:
          return b.lanes = 0, dj(a, b, c);
      }
      return Zi(a, b, c);
    }
    var zj, Aj, Bj, Cj;
    zj = function(a, b) {
      for (var c = b.child; null !== c; ) {
        if (5 === c.tag || 6 === c.tag) a.appendChild(c.stateNode);
        else if (4 !== c.tag && null !== c.child) {
          c.child.return = c;
          c = c.child;
          continue;
        }
        if (c === b) break;
        for (; null === c.sibling; ) {
          if (null === c.return || c.return === b) return;
          c = c.return;
        }
        c.sibling.return = c.return;
        c = c.sibling;
      }
    };
    Aj = function() {
    };
    Bj = function(a, b, c, d) {
      var e = a.memoizedProps;
      if (e !== d) {
        a = b.stateNode;
        xh(uh.current);
        var f = null;
        switch (c) {
          case "input":
            e = Ya(a, e);
            d = Ya(a, d);
            f = [];
            break;
          case "select":
            e = A({}, e, { value: void 0 });
            d = A({}, d, { value: void 0 });
            f = [];
            break;
          case "textarea":
            e = gb(a, e);
            d = gb(a, d);
            f = [];
            break;
          default:
            "function" !== typeof e.onClick && "function" === typeof d.onClick && (a.onclick = Bf);
        }
        ub(c, d);
        var g;
        c = null;
        for (l in e) if (!d.hasOwnProperty(l) && e.hasOwnProperty(l) && null != e[l]) if ("style" === l) {
          var h = e[l];
          for (g in h) h.hasOwnProperty(g) && (c || (c = {}), c[g] = "");
        } else "dangerouslySetInnerHTML" !== l && "children" !== l && "suppressContentEditableWarning" !== l && "suppressHydrationWarning" !== l && "autoFocus" !== l && (ea.hasOwnProperty(l) ? f || (f = []) : (f = f || []).push(l, null));
        for (l in d) {
          var k = d[l];
          h = null != e ? e[l] : void 0;
          if (d.hasOwnProperty(l) && k !== h && (null != k || null != h)) if ("style" === l) if (h) {
            for (g in h) !h.hasOwnProperty(g) || k && k.hasOwnProperty(g) || (c || (c = {}), c[g] = "");
            for (g in k) k.hasOwnProperty(g) && h[g] !== k[g] && (c || (c = {}), c[g] = k[g]);
          } else c || (f || (f = []), f.push(
            l,
            c
          )), c = k;
          else "dangerouslySetInnerHTML" === l ? (k = k ? k.__html : void 0, h = h ? h.__html : void 0, null != k && h !== k && (f = f || []).push(l, k)) : "children" === l ? "string" !== typeof k && "number" !== typeof k || (f = f || []).push(l, "" + k) : "suppressContentEditableWarning" !== l && "suppressHydrationWarning" !== l && (ea.hasOwnProperty(l) ? (null != k && "onScroll" === l && D("scroll", a), f || h === k || (f = [])) : (f = f || []).push(l, k));
        }
        c && (f = f || []).push("style", c);
        var l = f;
        if (b.updateQueue = l) b.flags |= 4;
      }
    };
    Cj = function(a, b, c, d) {
      c !== d && (b.flags |= 4);
    };
    function Dj(a, b) {
      if (!I) switch (a.tailMode) {
        case "hidden":
          b = a.tail;
          for (var c = null; null !== b; ) null !== b.alternate && (c = b), b = b.sibling;
          null === c ? a.tail = null : c.sibling = null;
          break;
        case "collapsed":
          c = a.tail;
          for (var d = null; null !== c; ) null !== c.alternate && (d = c), c = c.sibling;
          null === d ? b || null === a.tail ? a.tail = null : a.tail.sibling = null : d.sibling = null;
      }
    }
    function S(a) {
      var b = null !== a.alternate && a.alternate.child === a.child, c = 0, d = 0;
      if (b) for (var e = a.child; null !== e; ) c |= e.lanes | e.childLanes, d |= e.subtreeFlags & 14680064, d |= e.flags & 14680064, e.return = a, e = e.sibling;
      else for (e = a.child; null !== e; ) c |= e.lanes | e.childLanes, d |= e.subtreeFlags, d |= e.flags, e.return = a, e = e.sibling;
      a.subtreeFlags |= d;
      a.childLanes = c;
      return b;
    }
    function Ej(a, b, c) {
      var d = b.pendingProps;
      wg(b);
      switch (b.tag) {
        case 2:
        case 16:
        case 15:
        case 0:
        case 11:
        case 7:
        case 8:
        case 12:
        case 9:
        case 14:
          return S(b), null;
        case 1:
          return Zf(b.type) && $f(), S(b), null;
        case 3:
          d = b.stateNode;
          zh();
          E(Wf);
          E(H);
          Eh();
          d.pendingContext && (d.context = d.pendingContext, d.pendingContext = null);
          if (null === a || null === a.child) Gg(b) ? b.flags |= 4 : null === a || a.memoizedState.isDehydrated && 0 === (b.flags & 256) || (b.flags |= 1024, null !== zg && (Fj(zg), zg = null));
          Aj(a, b);
          S(b);
          return null;
        case 5:
          Bh(b);
          var e = xh(wh.current);
          c = b.type;
          if (null !== a && null != b.stateNode) Bj(a, b, c, d, e), a.ref !== b.ref && (b.flags |= 512, b.flags |= 2097152);
          else {
            if (!d) {
              if (null === b.stateNode) throw Error(p(166));
              S(b);
              return null;
            }
            a = xh(uh.current);
            if (Gg(b)) {
              d = b.stateNode;
              c = b.type;
              var f = b.memoizedProps;
              d[Of] = b;
              d[Pf] = f;
              a = 0 !== (b.mode & 1);
              switch (c) {
                case "dialog":
                  D("cancel", d);
                  D("close", d);
                  break;
                case "iframe":
                case "object":
                case "embed":
                  D("load", d);
                  break;
                case "video":
                case "audio":
                  for (e = 0; e < lf.length; e++) D(lf[e], d);
                  break;
                case "source":
                  D("error", d);
                  break;
                case "img":
                case "image":
                case "link":
                  D(
                    "error",
                    d
                  );
                  D("load", d);
                  break;
                case "details":
                  D("toggle", d);
                  break;
                case "input":
                  Za(d, f);
                  D("invalid", d);
                  break;
                case "select":
                  d._wrapperState = { wasMultiple: !!f.multiple };
                  D("invalid", d);
                  break;
                case "textarea":
                  hb(d, f), D("invalid", d);
              }
              ub(c, f);
              e = null;
              for (var g in f) if (f.hasOwnProperty(g)) {
                var h = f[g];
                "children" === g ? "string" === typeof h ? d.textContent !== h && (true !== f.suppressHydrationWarning && Af(d.textContent, h, a), e = ["children", h]) : "number" === typeof h && d.textContent !== "" + h && (true !== f.suppressHydrationWarning && Af(
                  d.textContent,
                  h,
                  a
                ), e = ["children", "" + h]) : ea.hasOwnProperty(g) && null != h && "onScroll" === g && D("scroll", d);
              }
              switch (c) {
                case "input":
                  Va(d);
                  db(d, f, true);
                  break;
                case "textarea":
                  Va(d);
                  jb(d);
                  break;
                case "select":
                case "option":
                  break;
                default:
                  "function" === typeof f.onClick && (d.onclick = Bf);
              }
              d = e;
              b.updateQueue = d;
              null !== d && (b.flags |= 4);
            } else {
              g = 9 === e.nodeType ? e : e.ownerDocument;
              "http://www.w3.org/1999/xhtml" === a && (a = kb(c));
              "http://www.w3.org/1999/xhtml" === a ? "script" === c ? (a = g.createElement("div"), a.innerHTML = "<script><\/script>", a = a.removeChild(a.firstChild)) : "string" === typeof d.is ? a = g.createElement(c, { is: d.is }) : (a = g.createElement(c), "select" === c && (g = a, d.multiple ? g.multiple = true : d.size && (g.size = d.size))) : a = g.createElementNS(a, c);
              a[Of] = b;
              a[Pf] = d;
              zj(a, b, false, false);
              b.stateNode = a;
              a: {
                g = vb(c, d);
                switch (c) {
                  case "dialog":
                    D("cancel", a);
                    D("close", a);
                    e = d;
                    break;
                  case "iframe":
                  case "object":
                  case "embed":
                    D("load", a);
                    e = d;
                    break;
                  case "video":
                  case "audio":
                    for (e = 0; e < lf.length; e++) D(lf[e], a);
                    e = d;
                    break;
                  case "source":
                    D("error", a);
                    e = d;
                    break;
                  case "img":
                  case "image":
                  case "link":
                    D(
                      "error",
                      a
                    );
                    D("load", a);
                    e = d;
                    break;
                  case "details":
                    D("toggle", a);
                    e = d;
                    break;
                  case "input":
                    Za(a, d);
                    e = Ya(a, d);
                    D("invalid", a);
                    break;
                  case "option":
                    e = d;
                    break;
                  case "select":
                    a._wrapperState = { wasMultiple: !!d.multiple };
                    e = A({}, d, { value: void 0 });
                    D("invalid", a);
                    break;
                  case "textarea":
                    hb(a, d);
                    e = gb(a, d);
                    D("invalid", a);
                    break;
                  default:
                    e = d;
                }
                ub(c, e);
                h = e;
                for (f in h) if (h.hasOwnProperty(f)) {
                  var k = h[f];
                  "style" === f ? sb(a, k) : "dangerouslySetInnerHTML" === f ? (k = k ? k.__html : void 0, null != k && nb(a, k)) : "children" === f ? "string" === typeof k ? ("textarea" !== c || "" !== k) && ob(a, k) : "number" === typeof k && ob(a, "" + k) : "suppressContentEditableWarning" !== f && "suppressHydrationWarning" !== f && "autoFocus" !== f && (ea.hasOwnProperty(f) ? null != k && "onScroll" === f && D("scroll", a) : null != k && ta(a, f, k, g));
                }
                switch (c) {
                  case "input":
                    Va(a);
                    db(a, d, false);
                    break;
                  case "textarea":
                    Va(a);
                    jb(a);
                    break;
                  case "option":
                    null != d.value && a.setAttribute("value", "" + Sa(d.value));
                    break;
                  case "select":
                    a.multiple = !!d.multiple;
                    f = d.value;
                    null != f ? fb(a, !!d.multiple, f, false) : null != d.defaultValue && fb(
                      a,
                      !!d.multiple,
                      d.defaultValue,
                      true
                    );
                    break;
                  default:
                    "function" === typeof e.onClick && (a.onclick = Bf);
                }
                switch (c) {
                  case "button":
                  case "input":
                  case "select":
                  case "textarea":
                    d = !!d.autoFocus;
                    break a;
                  case "img":
                    d = true;
                    break a;
                  default:
                    d = false;
                }
              }
              d && (b.flags |= 4);
            }
            null !== b.ref && (b.flags |= 512, b.flags |= 2097152);
          }
          S(b);
          return null;
        case 6:
          if (a && null != b.stateNode) Cj(a, b, a.memoizedProps, d);
          else {
            if ("string" !== typeof d && null === b.stateNode) throw Error(p(166));
            c = xh(wh.current);
            xh(uh.current);
            if (Gg(b)) {
              d = b.stateNode;
              c = b.memoizedProps;
              d[Of] = b;
              if (f = d.nodeValue !== c) {
                if (a = xg, null !== a) switch (a.tag) {
                  case 3:
                    Af(d.nodeValue, c, 0 !== (a.mode & 1));
                    break;
                  case 5:
                    true !== a.memoizedProps.suppressHydrationWarning && Af(d.nodeValue, c, 0 !== (a.mode & 1));
                }
              }
              f && (b.flags |= 4);
            } else d = (9 === c.nodeType ? c : c.ownerDocument).createTextNode(d), d[Of] = b, b.stateNode = d;
          }
          S(b);
          return null;
        case 13:
          E(L);
          d = b.memoizedState;
          if (null === a || null !== a.memoizedState && null !== a.memoizedState.dehydrated) {
            if (I && null !== yg && 0 !== (b.mode & 1) && 0 === (b.flags & 128)) Hg(), Ig(), b.flags |= 98560, f = false;
            else if (f = Gg(b), null !== d && null !== d.dehydrated) {
              if (null === a) {
                if (!f) throw Error(p(318));
                f = b.memoizedState;
                f = null !== f ? f.dehydrated : null;
                if (!f) throw Error(p(317));
                f[Of] = b;
              } else Ig(), 0 === (b.flags & 128) && (b.memoizedState = null), b.flags |= 4;
              S(b);
              f = false;
            } else null !== zg && (Fj(zg), zg = null), f = true;
            if (!f) return b.flags & 65536 ? b : null;
          }
          if (0 !== (b.flags & 128)) return b.lanes = c, b;
          d = null !== d;
          d !== (null !== a && null !== a.memoizedState) && d && (b.child.flags |= 8192, 0 !== (b.mode & 1) && (null === a || 0 !== (L.current & 1) ? 0 === T && (T = 3) : tj()));
          null !== b.updateQueue && (b.flags |= 4);
          S(b);
          return null;
        case 4:
          return zh(), Aj(a, b), null === a && sf(b.stateNode.containerInfo), S(b), null;
        case 10:
          return ah(b.type._context), S(b), null;
        case 17:
          return Zf(b.type) && $f(), S(b), null;
        case 19:
          E(L);
          f = b.memoizedState;
          if (null === f) return S(b), null;
          d = 0 !== (b.flags & 128);
          g = f.rendering;
          if (null === g) if (d) Dj(f, false);
          else {
            if (0 !== T || null !== a && 0 !== (a.flags & 128)) for (a = b.child; null !== a; ) {
              g = Ch(a);
              if (null !== g) {
                b.flags |= 128;
                Dj(f, false);
                d = g.updateQueue;
                null !== d && (b.updateQueue = d, b.flags |= 4);
                b.subtreeFlags = 0;
                d = c;
                for (c = b.child; null !== c; ) f = c, a = d, f.flags &= 14680066, g = f.alternate, null === g ? (f.childLanes = 0, f.lanes = a, f.child = null, f.subtreeFlags = 0, f.memoizedProps = null, f.memoizedState = null, f.updateQueue = null, f.dependencies = null, f.stateNode = null) : (f.childLanes = g.childLanes, f.lanes = g.lanes, f.child = g.child, f.subtreeFlags = 0, f.deletions = null, f.memoizedProps = g.memoizedProps, f.memoizedState = g.memoizedState, f.updateQueue = g.updateQueue, f.type = g.type, a = g.dependencies, f.dependencies = null === a ? null : { lanes: a.lanes, firstContext: a.firstContext }), c = c.sibling;
                G(L, L.current & 1 | 2);
                return b.child;
              }
              a = a.sibling;
            }
            null !== f.tail && B() > Gj && (b.flags |= 128, d = true, Dj(f, false), b.lanes = 4194304);
          }
          else {
            if (!d) if (a = Ch(g), null !== a) {
              if (b.flags |= 128, d = true, c = a.updateQueue, null !== c && (b.updateQueue = c, b.flags |= 4), Dj(f, true), null === f.tail && "hidden" === f.tailMode && !g.alternate && !I) return S(b), null;
            } else 2 * B() - f.renderingStartTime > Gj && 1073741824 !== c && (b.flags |= 128, d = true, Dj(f, false), b.lanes = 4194304);
            f.isBackwards ? (g.sibling = b.child, b.child = g) : (c = f.last, null !== c ? c.sibling = g : b.child = g, f.last = g);
          }
          if (null !== f.tail) return b = f.tail, f.rendering = b, f.tail = b.sibling, f.renderingStartTime = B(), b.sibling = null, c = L.current, G(L, d ? c & 1 | 2 : c & 1), b;
          S(b);
          return null;
        case 22:
        case 23:
          return Hj(), d = null !== b.memoizedState, null !== a && null !== a.memoizedState !== d && (b.flags |= 8192), d && 0 !== (b.mode & 1) ? 0 !== (fj & 1073741824) && (S(b), b.subtreeFlags & 6 && (b.flags |= 8192)) : S(b), null;
        case 24:
          return null;
        case 25:
          return null;
      }
      throw Error(p(156, b.tag));
    }
    function Ij(a, b) {
      wg(b);
      switch (b.tag) {
        case 1:
          return Zf(b.type) && $f(), a = b.flags, a & 65536 ? (b.flags = a & -65537 | 128, b) : null;
        case 3:
          return zh(), E(Wf), E(H), Eh(), a = b.flags, 0 !== (a & 65536) && 0 === (a & 128) ? (b.flags = a & -65537 | 128, b) : null;
        case 5:
          return Bh(b), null;
        case 13:
          E(L);
          a = b.memoizedState;
          if (null !== a && null !== a.dehydrated) {
            if (null === b.alternate) throw Error(p(340));
            Ig();
          }
          a = b.flags;
          return a & 65536 ? (b.flags = a & -65537 | 128, b) : null;
        case 19:
          return E(L), null;
        case 4:
          return zh(), null;
        case 10:
          return ah(b.type._context), null;
        case 22:
        case 23:
          return Hj(), null;
        case 24:
          return null;
        default:
          return null;
      }
    }
    var Jj = false, U = false, Kj = "function" === typeof WeakSet ? WeakSet : Set, V = null;
    function Lj(a, b) {
      var c = a.ref;
      if (null !== c) if ("function" === typeof c) try {
        c(null);
      } catch (d) {
        W(a, b, d);
      }
      else c.current = null;
    }
    function Mj(a, b, c) {
      try {
        c();
      } catch (d) {
        W(a, b, d);
      }
    }
    var Nj = false;
    function Oj(a, b) {
      Cf = dd;
      a = Me();
      if (Ne(a)) {
        if ("selectionStart" in a) var c = { start: a.selectionStart, end: a.selectionEnd };
        else a: {
          c = (c = a.ownerDocument) && c.defaultView || window;
          var d = c.getSelection && c.getSelection();
          if (d && 0 !== d.rangeCount) {
            c = d.anchorNode;
            var e = d.anchorOffset, f = d.focusNode;
            d = d.focusOffset;
            try {
              c.nodeType, f.nodeType;
            } catch (F) {
              c = null;
              break a;
            }
            var g = 0, h = -1, k = -1, l = 0, m = 0, q = a, r = null;
            b: for (; ; ) {
              for (var y; ; ) {
                q !== c || 0 !== e && 3 !== q.nodeType || (h = g + e);
                q !== f || 0 !== d && 3 !== q.nodeType || (k = g + d);
                3 === q.nodeType && (g += q.nodeValue.length);
                if (null === (y = q.firstChild)) break;
                r = q;
                q = y;
              }
              for (; ; ) {
                if (q === a) break b;
                r === c && ++l === e && (h = g);
                r === f && ++m === d && (k = g);
                if (null !== (y = q.nextSibling)) break;
                q = r;
                r = q.parentNode;
              }
              q = y;
            }
            c = -1 === h || -1 === k ? null : { start: h, end: k };
          } else c = null;
        }
        c = c || { start: 0, end: 0 };
      } else c = null;
      Df = { focusedElem: a, selectionRange: c };
      dd = false;
      for (V = b; null !== V; ) if (b = V, a = b.child, 0 !== (b.subtreeFlags & 1028) && null !== a) a.return = b, V = a;
      else for (; null !== V; ) {
        b = V;
        try {
          var n = b.alternate;
          if (0 !== (b.flags & 1024)) switch (b.tag) {
            case 0:
            case 11:
            case 15:
              break;
            case 1:
              if (null !== n) {
                var t = n.memoizedProps, J = n.memoizedState, x = b.stateNode, w = x.getSnapshotBeforeUpdate(b.elementType === b.type ? t : Ci(b.type, t), J);
                x.__reactInternalSnapshotBeforeUpdate = w;
              }
              break;
            case 3:
              var u = b.stateNode.containerInfo;
              1 === u.nodeType ? u.textContent = "" : 9 === u.nodeType && u.documentElement && u.removeChild(u.documentElement);
              break;
            case 5:
            case 6:
            case 4:
            case 17:
              break;
            default:
              throw Error(p(163));
          }
        } catch (F) {
          W(b, b.return, F);
        }
        a = b.sibling;
        if (null !== a) {
          a.return = b.return;
          V = a;
          break;
        }
        V = b.return;
      }
      n = Nj;
      Nj = false;
      return n;
    }
    function Pj(a, b, c) {
      var d = b.updateQueue;
      d = null !== d ? d.lastEffect : null;
      if (null !== d) {
        var e = d = d.next;
        do {
          if ((e.tag & a) === a) {
            var f = e.destroy;
            e.destroy = void 0;
            void 0 !== f && Mj(b, c, f);
          }
          e = e.next;
        } while (e !== d);
      }
    }
    function Qj(a, b) {
      b = b.updateQueue;
      b = null !== b ? b.lastEffect : null;
      if (null !== b) {
        var c = b = b.next;
        do {
          if ((c.tag & a) === a) {
            var d = c.create;
            c.destroy = d();
          }
          c = c.next;
        } while (c !== b);
      }
    }
    function Rj(a) {
      var b = a.ref;
      if (null !== b) {
        var c = a.stateNode;
        switch (a.tag) {
          case 5:
            a = c;
            break;
          default:
            a = c;
        }
        "function" === typeof b ? b(a) : b.current = a;
      }
    }
    function Sj(a) {
      var b = a.alternate;
      null !== b && (a.alternate = null, Sj(b));
      a.child = null;
      a.deletions = null;
      a.sibling = null;
      5 === a.tag && (b = a.stateNode, null !== b && (delete b[Of], delete b[Pf], delete b[of], delete b[Qf], delete b[Rf]));
      a.stateNode = null;
      a.return = null;
      a.dependencies = null;
      a.memoizedProps = null;
      a.memoizedState = null;
      a.pendingProps = null;
      a.stateNode = null;
      a.updateQueue = null;
    }
    function Tj(a) {
      return 5 === a.tag || 3 === a.tag || 4 === a.tag;
    }
    function Uj(a) {
      a: for (; ; ) {
        for (; null === a.sibling; ) {
          if (null === a.return || Tj(a.return)) return null;
          a = a.return;
        }
        a.sibling.return = a.return;
        for (a = a.sibling; 5 !== a.tag && 6 !== a.tag && 18 !== a.tag; ) {
          if (a.flags & 2) continue a;
          if (null === a.child || 4 === a.tag) continue a;
          else a.child.return = a, a = a.child;
        }
        if (!(a.flags & 2)) return a.stateNode;
      }
    }
    function Vj(a, b, c) {
      var d = a.tag;
      if (5 === d || 6 === d) a = a.stateNode, b ? 8 === c.nodeType ? c.parentNode.insertBefore(a, b) : c.insertBefore(a, b) : (8 === c.nodeType ? (b = c.parentNode, b.insertBefore(a, c)) : (b = c, b.appendChild(a)), c = c._reactRootContainer, null !== c && void 0 !== c || null !== b.onclick || (b.onclick = Bf));
      else if (4 !== d && (a = a.child, null !== a)) for (Vj(a, b, c), a = a.sibling; null !== a; ) Vj(a, b, c), a = a.sibling;
    }
    function Wj(a, b, c) {
      var d = a.tag;
      if (5 === d || 6 === d) a = a.stateNode, b ? c.insertBefore(a, b) : c.appendChild(a);
      else if (4 !== d && (a = a.child, null !== a)) for (Wj(a, b, c), a = a.sibling; null !== a; ) Wj(a, b, c), a = a.sibling;
    }
    var X = null, Xj = false;
    function Yj(a, b, c) {
      for (c = c.child; null !== c; ) Zj(a, b, c), c = c.sibling;
    }
    function Zj(a, b, c) {
      if (lc && "function" === typeof lc.onCommitFiberUnmount) try {
        lc.onCommitFiberUnmount(kc, c);
      } catch (h) {
      }
      switch (c.tag) {
        case 5:
          U || Lj(c, b);
        case 6:
          var d = X, e = Xj;
          X = null;
          Yj(a, b, c);
          X = d;
          Xj = e;
          null !== X && (Xj ? (a = X, c = c.stateNode, 8 === a.nodeType ? a.parentNode.removeChild(c) : a.removeChild(c)) : X.removeChild(c.stateNode));
          break;
        case 18:
          null !== X && (Xj ? (a = X, c = c.stateNode, 8 === a.nodeType ? Kf(a.parentNode, c) : 1 === a.nodeType && Kf(a, c), bd(a)) : Kf(X, c.stateNode));
          break;
        case 4:
          d = X;
          e = Xj;
          X = c.stateNode.containerInfo;
          Xj = true;
          Yj(a, b, c);
          X = d;
          Xj = e;
          break;
        case 0:
        case 11:
        case 14:
        case 15:
          if (!U && (d = c.updateQueue, null !== d && (d = d.lastEffect, null !== d))) {
            e = d = d.next;
            do {
              var f = e, g = f.destroy;
              f = f.tag;
              void 0 !== g && (0 !== (f & 2) ? Mj(c, b, g) : 0 !== (f & 4) && Mj(c, b, g));
              e = e.next;
            } while (e !== d);
          }
          Yj(a, b, c);
          break;
        case 1:
          if (!U && (Lj(c, b), d = c.stateNode, "function" === typeof d.componentWillUnmount)) try {
            d.props = c.memoizedProps, d.state = c.memoizedState, d.componentWillUnmount();
          } catch (h) {
            W(c, b, h);
          }
          Yj(a, b, c);
          break;
        case 21:
          Yj(a, b, c);
          break;
        case 22:
          c.mode & 1 ? (U = (d = U) || null !== c.memoizedState, Yj(a, b, c), U = d) : Yj(a, b, c);
          break;
        default:
          Yj(a, b, c);
      }
    }
    function ak(a) {
      var b = a.updateQueue;
      if (null !== b) {
        a.updateQueue = null;
        var c = a.stateNode;
        null === c && (c = a.stateNode = new Kj());
        b.forEach(function(b2) {
          var d = bk.bind(null, a, b2);
          c.has(b2) || (c.add(b2), b2.then(d, d));
        });
      }
    }
    function ck(a, b) {
      var c = b.deletions;
      if (null !== c) for (var d = 0; d < c.length; d++) {
        var e = c[d];
        try {
          var f = a, g = b, h = g;
          a: for (; null !== h; ) {
            switch (h.tag) {
              case 5:
                X = h.stateNode;
                Xj = false;
                break a;
              case 3:
                X = h.stateNode.containerInfo;
                Xj = true;
                break a;
              case 4:
                X = h.stateNode.containerInfo;
                Xj = true;
                break a;
            }
            h = h.return;
          }
          if (null === X) throw Error(p(160));
          Zj(f, g, e);
          X = null;
          Xj = false;
          var k = e.alternate;
          null !== k && (k.return = null);
          e.return = null;
        } catch (l) {
          W(e, b, l);
        }
      }
      if (b.subtreeFlags & 12854) for (b = b.child; null !== b; ) dk(b, a), b = b.sibling;
    }
    function dk(a, b) {
      var c = a.alternate, d = a.flags;
      switch (a.tag) {
        case 0:
        case 11:
        case 14:
        case 15:
          ck(b, a);
          ek(a);
          if (d & 4) {
            try {
              Pj(3, a, a.return), Qj(3, a);
            } catch (t) {
              W(a, a.return, t);
            }
            try {
              Pj(5, a, a.return);
            } catch (t) {
              W(a, a.return, t);
            }
          }
          break;
        case 1:
          ck(b, a);
          ek(a);
          d & 512 && null !== c && Lj(c, c.return);
          break;
        case 5:
          ck(b, a);
          ek(a);
          d & 512 && null !== c && Lj(c, c.return);
          if (a.flags & 32) {
            var e = a.stateNode;
            try {
              ob(e, "");
            } catch (t) {
              W(a, a.return, t);
            }
          }
          if (d & 4 && (e = a.stateNode, null != e)) {
            var f = a.memoizedProps, g = null !== c ? c.memoizedProps : f, h = a.type, k = a.updateQueue;
            a.updateQueue = null;
            if (null !== k) try {
              "input" === h && "radio" === f.type && null != f.name && ab(e, f);
              vb(h, g);
              var l = vb(h, f);
              for (g = 0; g < k.length; g += 2) {
                var m = k[g], q = k[g + 1];
                "style" === m ? sb(e, q) : "dangerouslySetInnerHTML" === m ? nb(e, q) : "children" === m ? ob(e, q) : ta(e, m, q, l);
              }
              switch (h) {
                case "input":
                  bb(e, f);
                  break;
                case "textarea":
                  ib(e, f);
                  break;
                case "select":
                  var r = e._wrapperState.wasMultiple;
                  e._wrapperState.wasMultiple = !!f.multiple;
                  var y = f.value;
                  null != y ? fb(e, !!f.multiple, y, false) : r !== !!f.multiple && (null != f.defaultValue ? fb(
                    e,
                    !!f.multiple,
                    f.defaultValue,
                    true
                  ) : fb(e, !!f.multiple, f.multiple ? [] : "", false));
              }
              e[Pf] = f;
            } catch (t) {
              W(a, a.return, t);
            }
          }
          break;
        case 6:
          ck(b, a);
          ek(a);
          if (d & 4) {
            if (null === a.stateNode) throw Error(p(162));
            e = a.stateNode;
            f = a.memoizedProps;
            try {
              e.nodeValue = f;
            } catch (t) {
              W(a, a.return, t);
            }
          }
          break;
        case 3:
          ck(b, a);
          ek(a);
          if (d & 4 && null !== c && c.memoizedState.isDehydrated) try {
            bd(b.containerInfo);
          } catch (t) {
            W(a, a.return, t);
          }
          break;
        case 4:
          ck(b, a);
          ek(a);
          break;
        case 13:
          ck(b, a);
          ek(a);
          e = a.child;
          e.flags & 8192 && (f = null !== e.memoizedState, e.stateNode.isHidden = f, !f || null !== e.alternate && null !== e.alternate.memoizedState || (fk = B()));
          d & 4 && ak(a);
          break;
        case 22:
          m = null !== c && null !== c.memoizedState;
          a.mode & 1 ? (U = (l = U) || m, ck(b, a), U = l) : ck(b, a);
          ek(a);
          if (d & 8192) {
            l = null !== a.memoizedState;
            if ((a.stateNode.isHidden = l) && !m && 0 !== (a.mode & 1)) for (V = a, m = a.child; null !== m; ) {
              for (q = V = m; null !== V; ) {
                r = V;
                y = r.child;
                switch (r.tag) {
                  case 0:
                  case 11:
                  case 14:
                  case 15:
                    Pj(4, r, r.return);
                    break;
                  case 1:
                    Lj(r, r.return);
                    var n = r.stateNode;
                    if ("function" === typeof n.componentWillUnmount) {
                      d = r;
                      c = r.return;
                      try {
                        b = d, n.props = b.memoizedProps, n.state = b.memoizedState, n.componentWillUnmount();
                      } catch (t) {
                        W(d, c, t);
                      }
                    }
                    break;
                  case 5:
                    Lj(r, r.return);
                    break;
                  case 22:
                    if (null !== r.memoizedState) {
                      gk(q);
                      continue;
                    }
                }
                null !== y ? (y.return = r, V = y) : gk(q);
              }
              m = m.sibling;
            }
            a: for (m = null, q = a; ; ) {
              if (5 === q.tag) {
                if (null === m) {
                  m = q;
                  try {
                    e = q.stateNode, l ? (f = e.style, "function" === typeof f.setProperty ? f.setProperty("display", "none", "important") : f.display = "none") : (h = q.stateNode, k = q.memoizedProps.style, g = void 0 !== k && null !== k && k.hasOwnProperty("display") ? k.display : null, h.style.display = rb("display", g));
                  } catch (t) {
                    W(a, a.return, t);
                  }
                }
              } else if (6 === q.tag) {
                if (null === m) try {
                  q.stateNode.nodeValue = l ? "" : q.memoizedProps;
                } catch (t) {
                  W(a, a.return, t);
                }
              } else if ((22 !== q.tag && 23 !== q.tag || null === q.memoizedState || q === a) && null !== q.child) {
                q.child.return = q;
                q = q.child;
                continue;
              }
              if (q === a) break a;
              for (; null === q.sibling; ) {
                if (null === q.return || q.return === a) break a;
                m === q && (m = null);
                q = q.return;
              }
              m === q && (m = null);
              q.sibling.return = q.return;
              q = q.sibling;
            }
          }
          break;
        case 19:
          ck(b, a);
          ek(a);
          d & 4 && ak(a);
          break;
        case 21:
          break;
        default:
          ck(
            b,
            a
          ), ek(a);
      }
    }
    function ek(a) {
      var b = a.flags;
      if (b & 2) {
        try {
          a: {
            for (var c = a.return; null !== c; ) {
              if (Tj(c)) {
                var d = c;
                break a;
              }
              c = c.return;
            }
            throw Error(p(160));
          }
          switch (d.tag) {
            case 5:
              var e = d.stateNode;
              d.flags & 32 && (ob(e, ""), d.flags &= -33);
              var f = Uj(a);
              Wj(a, f, e);
              break;
            case 3:
            case 4:
              var g = d.stateNode.containerInfo, h = Uj(a);
              Vj(a, h, g);
              break;
            default:
              throw Error(p(161));
          }
        } catch (k) {
          W(a, a.return, k);
        }
        a.flags &= -3;
      }
      b & 4096 && (a.flags &= -4097);
    }
    function hk(a, b, c) {
      V = a;
      ik(a);
    }
    function ik(a, b, c) {
      for (var d = 0 !== (a.mode & 1); null !== V; ) {
        var e = V, f = e.child;
        if (22 === e.tag && d) {
          var g = null !== e.memoizedState || Jj;
          if (!g) {
            var h = e.alternate, k = null !== h && null !== h.memoizedState || U;
            h = Jj;
            var l = U;
            Jj = g;
            if ((U = k) && !l) for (V = e; null !== V; ) g = V, k = g.child, 22 === g.tag && null !== g.memoizedState ? jk(e) : null !== k ? (k.return = g, V = k) : jk(e);
            for (; null !== f; ) V = f, ik(f), f = f.sibling;
            V = e;
            Jj = h;
            U = l;
          }
          kk(a);
        } else 0 !== (e.subtreeFlags & 8772) && null !== f ? (f.return = e, V = f) : kk(a);
      }
    }
    function kk(a) {
      for (; null !== V; ) {
        var b = V;
        if (0 !== (b.flags & 8772)) {
          var c = b.alternate;
          try {
            if (0 !== (b.flags & 8772)) switch (b.tag) {
              case 0:
              case 11:
              case 15:
                U || Qj(5, b);
                break;
              case 1:
                var d = b.stateNode;
                if (b.flags & 4 && !U) if (null === c) d.componentDidMount();
                else {
                  var e = b.elementType === b.type ? c.memoizedProps : Ci(b.type, c.memoizedProps);
                  d.componentDidUpdate(e, c.memoizedState, d.__reactInternalSnapshotBeforeUpdate);
                }
                var f = b.updateQueue;
                null !== f && sh(b, f, d);
                break;
              case 3:
                var g = b.updateQueue;
                if (null !== g) {
                  c = null;
                  if (null !== b.child) switch (b.child.tag) {
                    case 5:
                      c = b.child.stateNode;
                      break;
                    case 1:
                      c = b.child.stateNode;
                  }
                  sh(b, g, c);
                }
                break;
              case 5:
                var h = b.stateNode;
                if (null === c && b.flags & 4) {
                  c = h;
                  var k = b.memoizedProps;
                  switch (b.type) {
                    case "button":
                    case "input":
                    case "select":
                    case "textarea":
                      k.autoFocus && c.focus();
                      break;
                    case "img":
                      k.src && (c.src = k.src);
                  }
                }
                break;
              case 6:
                break;
              case 4:
                break;
              case 12:
                break;
              case 13:
                if (null === b.memoizedState) {
                  var l = b.alternate;
                  if (null !== l) {
                    var m = l.memoizedState;
                    if (null !== m) {
                      var q = m.dehydrated;
                      null !== q && bd(q);
                    }
                  }
                }
                break;
              case 19:
              case 17:
              case 21:
              case 22:
              case 23:
              case 25:
                break;
              default:
                throw Error(p(163));
            }
            U || b.flags & 512 && Rj(b);
          } catch (r) {
            W(b, b.return, r);
          }
        }
        if (b === a) {
          V = null;
          break;
        }
        c = b.sibling;
        if (null !== c) {
          c.return = b.return;
          V = c;
          break;
        }
        V = b.return;
      }
    }
    function gk(a) {
      for (; null !== V; ) {
        var b = V;
        if (b === a) {
          V = null;
          break;
        }
        var c = b.sibling;
        if (null !== c) {
          c.return = b.return;
          V = c;
          break;
        }
        V = b.return;
      }
    }
    function jk(a) {
      for (; null !== V; ) {
        var b = V;
        try {
          switch (b.tag) {
            case 0:
            case 11:
            case 15:
              var c = b.return;
              try {
                Qj(4, b);
              } catch (k) {
                W(b, c, k);
              }
              break;
            case 1:
              var d = b.stateNode;
              if ("function" === typeof d.componentDidMount) {
                var e = b.return;
                try {
                  d.componentDidMount();
                } catch (k) {
                  W(b, e, k);
                }
              }
              var f = b.return;
              try {
                Rj(b);
              } catch (k) {
                W(b, f, k);
              }
              break;
            case 5:
              var g = b.return;
              try {
                Rj(b);
              } catch (k) {
                W(b, g, k);
              }
          }
        } catch (k) {
          W(b, b.return, k);
        }
        if (b === a) {
          V = null;
          break;
        }
        var h = b.sibling;
        if (null !== h) {
          h.return = b.return;
          V = h;
          break;
        }
        V = b.return;
      }
    }
    var lk = Math.ceil, mk = ua.ReactCurrentDispatcher, nk = ua.ReactCurrentOwner, ok = ua.ReactCurrentBatchConfig, K = 0, Q = null, Y = null, Z = 0, fj = 0, ej = Uf(0), T = 0, pk = null, rh = 0, qk = 0, rk = 0, sk = null, tk = null, fk = 0, Gj = Infinity, uk = null, Oi = false, Pi = null, Ri = null, vk = false, wk = null, xk = 0, yk = 0, zk = null, Ak = -1, Bk = 0;
    function R() {
      return 0 !== (K & 6) ? B() : -1 !== Ak ? Ak : Ak = B();
    }
    function yi(a) {
      if (0 === (a.mode & 1)) return 1;
      if (0 !== (K & 2) && 0 !== Z) return Z & -Z;
      if (null !== Kg.transition) return 0 === Bk && (Bk = yc()), Bk;
      a = C;
      if (0 !== a) return a;
      a = window.event;
      a = void 0 === a ? 16 : jd(a.type);
      return a;
    }
    function gi(a, b, c, d) {
      if (50 < yk) throw yk = 0, zk = null, Error(p(185));
      Ac(a, c, d);
      if (0 === (K & 2) || a !== Q) a === Q && (0 === (K & 2) && (qk |= c), 4 === T && Ck(a, Z)), Dk(a, d), 1 === c && 0 === K && 0 === (b.mode & 1) && (Gj = B() + 500, fg && jg());
    }
    function Dk(a, b) {
      var c = a.callbackNode;
      wc(a, b);
      var d = uc(a, a === Q ? Z : 0);
      if (0 === d) null !== c && bc(c), a.callbackNode = null, a.callbackPriority = 0;
      else if (b = d & -d, a.callbackPriority !== b) {
        null != c && bc(c);
        if (1 === b) 0 === a.tag ? ig(Ek.bind(null, a)) : hg(Ek.bind(null, a)), Jf(function() {
          0 === (K & 6) && jg();
        }), c = null;
        else {
          switch (Dc(d)) {
            case 1:
              c = fc;
              break;
            case 4:
              c = gc;
              break;
            case 16:
              c = hc;
              break;
            case 536870912:
              c = jc;
              break;
            default:
              c = hc;
          }
          c = Fk(c, Gk.bind(null, a));
        }
        a.callbackPriority = b;
        a.callbackNode = c;
      }
    }
    function Gk(a, b) {
      Ak = -1;
      Bk = 0;
      if (0 !== (K & 6)) throw Error(p(327));
      var c = a.callbackNode;
      if (Hk() && a.callbackNode !== c) return null;
      var d = uc(a, a === Q ? Z : 0);
      if (0 === d) return null;
      if (0 !== (d & 30) || 0 !== (d & a.expiredLanes) || b) b = Ik(a, d);
      else {
        b = d;
        var e = K;
        K |= 2;
        var f = Jk();
        if (Q !== a || Z !== b) uk = null, Gj = B() + 500, Kk(a, b);
        do
          try {
            Lk();
            break;
          } catch (h) {
            Mk(a, h);
          }
        while (1);
        $g();
        mk.current = f;
        K = e;
        null !== Y ? b = 0 : (Q = null, Z = 0, b = T);
      }
      if (0 !== b) {
        2 === b && (e = xc(a), 0 !== e && (d = e, b = Nk(a, e)));
        if (1 === b) throw c = pk, Kk(a, 0), Ck(a, d), Dk(a, B()), c;
        if (6 === b) Ck(a, d);
        else {
          e = a.current.alternate;
          if (0 === (d & 30) && !Ok(e) && (b = Ik(a, d), 2 === b && (f = xc(a), 0 !== f && (d = f, b = Nk(a, f))), 1 === b)) throw c = pk, Kk(a, 0), Ck(a, d), Dk(a, B()), c;
          a.finishedWork = e;
          a.finishedLanes = d;
          switch (b) {
            case 0:
            case 1:
              throw Error(p(345));
            case 2:
              Pk(a, tk, uk);
              break;
            case 3:
              Ck(a, d);
              if ((d & 130023424) === d && (b = fk + 500 - B(), 10 < b)) {
                if (0 !== uc(a, 0)) break;
                e = a.suspendedLanes;
                if ((e & d) !== d) {
                  R();
                  a.pingedLanes |= a.suspendedLanes & e;
                  break;
                }
                a.timeoutHandle = Ff(Pk.bind(null, a, tk, uk), b);
                break;
              }
              Pk(a, tk, uk);
              break;
            case 4:
              Ck(a, d);
              if ((d & 4194240) === d) break;
              b = a.eventTimes;
              for (e = -1; 0 < d; ) {
                var g = 31 - oc(d);
                f = 1 << g;
                g = b[g];
                g > e && (e = g);
                d &= ~f;
              }
              d = e;
              d = B() - d;
              d = (120 > d ? 120 : 480 > d ? 480 : 1080 > d ? 1080 : 1920 > d ? 1920 : 3e3 > d ? 3e3 : 4320 > d ? 4320 : 1960 * lk(d / 1960)) - d;
              if (10 < d) {
                a.timeoutHandle = Ff(Pk.bind(null, a, tk, uk), d);
                break;
              }
              Pk(a, tk, uk);
              break;
            case 5:
              Pk(a, tk, uk);
              break;
            default:
              throw Error(p(329));
          }
        }
      }
      Dk(a, B());
      return a.callbackNode === c ? Gk.bind(null, a) : null;
    }
    function Nk(a, b) {
      var c = sk;
      a.current.memoizedState.isDehydrated && (Kk(a, b).flags |= 256);
      a = Ik(a, b);
      2 !== a && (b = tk, tk = c, null !== b && Fj(b));
      return a;
    }
    function Fj(a) {
      null === tk ? tk = a : tk.push.apply(tk, a);
    }
    function Ok(a) {
      for (var b = a; ; ) {
        if (b.flags & 16384) {
          var c = b.updateQueue;
          if (null !== c && (c = c.stores, null !== c)) for (var d = 0; d < c.length; d++) {
            var e = c[d], f = e.getSnapshot;
            e = e.value;
            try {
              if (!He(f(), e)) return false;
            } catch (g) {
              return false;
            }
          }
        }
        c = b.child;
        if (b.subtreeFlags & 16384 && null !== c) c.return = b, b = c;
        else {
          if (b === a) break;
          for (; null === b.sibling; ) {
            if (null === b.return || b.return === a) return true;
            b = b.return;
          }
          b.sibling.return = b.return;
          b = b.sibling;
        }
      }
      return true;
    }
    function Ck(a, b) {
      b &= ~rk;
      b &= ~qk;
      a.suspendedLanes |= b;
      a.pingedLanes &= ~b;
      for (a = a.expirationTimes; 0 < b; ) {
        var c = 31 - oc(b), d = 1 << c;
        a[c] = -1;
        b &= ~d;
      }
    }
    function Ek(a) {
      if (0 !== (K & 6)) throw Error(p(327));
      Hk();
      var b = uc(a, 0);
      if (0 === (b & 1)) return Dk(a, B()), null;
      var c = Ik(a, b);
      if (0 !== a.tag && 2 === c) {
        var d = xc(a);
        0 !== d && (b = d, c = Nk(a, d));
      }
      if (1 === c) throw c = pk, Kk(a, 0), Ck(a, b), Dk(a, B()), c;
      if (6 === c) throw Error(p(345));
      a.finishedWork = a.current.alternate;
      a.finishedLanes = b;
      Pk(a, tk, uk);
      Dk(a, B());
      return null;
    }
    function Qk(a, b) {
      var c = K;
      K |= 1;
      try {
        return a(b);
      } finally {
        K = c, 0 === K && (Gj = B() + 500, fg && jg());
      }
    }
    function Rk(a) {
      null !== wk && 0 === wk.tag && 0 === (K & 6) && Hk();
      var b = K;
      K |= 1;
      var c = ok.transition, d = C;
      try {
        if (ok.transition = null, C = 1, a) return a();
      } finally {
        C = d, ok.transition = c, K = b, 0 === (K & 6) && jg();
      }
    }
    function Hj() {
      fj = ej.current;
      E(ej);
    }
    function Kk(a, b) {
      a.finishedWork = null;
      a.finishedLanes = 0;
      var c = a.timeoutHandle;
      -1 !== c && (a.timeoutHandle = -1, Gf(c));
      if (null !== Y) for (c = Y.return; null !== c; ) {
        var d = c;
        wg(d);
        switch (d.tag) {
          case 1:
            d = d.type.childContextTypes;
            null !== d && void 0 !== d && $f();
            break;
          case 3:
            zh();
            E(Wf);
            E(H);
            Eh();
            break;
          case 5:
            Bh(d);
            break;
          case 4:
            zh();
            break;
          case 13:
            E(L);
            break;
          case 19:
            E(L);
            break;
          case 10:
            ah(d.type._context);
            break;
          case 22:
          case 23:
            Hj();
        }
        c = c.return;
      }
      Q = a;
      Y = a = Pg(a.current, null);
      Z = fj = b;
      T = 0;
      pk = null;
      rk = qk = rh = 0;
      tk = sk = null;
      if (null !== fh) {
        for (b = 0; b < fh.length; b++) if (c = fh[b], d = c.interleaved, null !== d) {
          c.interleaved = null;
          var e = d.next, f = c.pending;
          if (null !== f) {
            var g = f.next;
            f.next = e;
            d.next = g;
          }
          c.pending = d;
        }
        fh = null;
      }
      return a;
    }
    function Mk(a, b) {
      do {
        var c = Y;
        try {
          $g();
          Fh.current = Rh;
          if (Ih) {
            for (var d = M.memoizedState; null !== d; ) {
              var e = d.queue;
              null !== e && (e.pending = null);
              d = d.next;
            }
            Ih = false;
          }
          Hh = 0;
          O = N = M = null;
          Jh = false;
          Kh = 0;
          nk.current = null;
          if (null === c || null === c.return) {
            T = 1;
            pk = b;
            Y = null;
            break;
          }
          a: {
            var f = a, g = c.return, h = c, k = b;
            b = Z;
            h.flags |= 32768;
            if (null !== k && "object" === typeof k && "function" === typeof k.then) {
              var l = k, m = h, q = m.tag;
              if (0 === (m.mode & 1) && (0 === q || 11 === q || 15 === q)) {
                var r = m.alternate;
                r ? (m.updateQueue = r.updateQueue, m.memoizedState = r.memoizedState, m.lanes = r.lanes) : (m.updateQueue = null, m.memoizedState = null);
              }
              var y = Ui(g);
              if (null !== y) {
                y.flags &= -257;
                Vi(y, g, h, f, b);
                y.mode & 1 && Si(f, l, b);
                b = y;
                k = l;
                var n = b.updateQueue;
                if (null === n) {
                  var t = /* @__PURE__ */ new Set();
                  t.add(k);
                  b.updateQueue = t;
                } else n.add(k);
                break a;
              } else {
                if (0 === (b & 1)) {
                  Si(f, l, b);
                  tj();
                  break a;
                }
                k = Error(p(426));
              }
            } else if (I && h.mode & 1) {
              var J = Ui(g);
              if (null !== J) {
                0 === (J.flags & 65536) && (J.flags |= 256);
                Vi(J, g, h, f, b);
                Jg(Ji(k, h));
                break a;
              }
            }
            f = k = Ji(k, h);
            4 !== T && (T = 2);
            null === sk ? sk = [f] : sk.push(f);
            f = g;
            do {
              switch (f.tag) {
                case 3:
                  f.flags |= 65536;
                  b &= -b;
                  f.lanes |= b;
                  var x = Ni(f, k, b);
                  ph(f, x);
                  break a;
                case 1:
                  h = k;
                  var w = f.type, u = f.stateNode;
                  if (0 === (f.flags & 128) && ("function" === typeof w.getDerivedStateFromError || null !== u && "function" === typeof u.componentDidCatch && (null === Ri || !Ri.has(u)))) {
                    f.flags |= 65536;
                    b &= -b;
                    f.lanes |= b;
                    var F = Qi(f, h, b);
                    ph(f, F);
                    break a;
                  }
              }
              f = f.return;
            } while (null !== f);
          }
          Sk(c);
        } catch (na) {
          b = na;
          Y === c && null !== c && (Y = c = c.return);
          continue;
        }
        break;
      } while (1);
    }
    function Jk() {
      var a = mk.current;
      mk.current = Rh;
      return null === a ? Rh : a;
    }
    function tj() {
      if (0 === T || 3 === T || 2 === T) T = 4;
      null === Q || 0 === (rh & 268435455) && 0 === (qk & 268435455) || Ck(Q, Z);
    }
    function Ik(a, b) {
      var c = K;
      K |= 2;
      var d = Jk();
      if (Q !== a || Z !== b) uk = null, Kk(a, b);
      do
        try {
          Tk();
          break;
        } catch (e) {
          Mk(a, e);
        }
      while (1);
      $g();
      K = c;
      mk.current = d;
      if (null !== Y) throw Error(p(261));
      Q = null;
      Z = 0;
      return T;
    }
    function Tk() {
      for (; null !== Y; ) Uk(Y);
    }
    function Lk() {
      for (; null !== Y && !cc(); ) Uk(Y);
    }
    function Uk(a) {
      var b = Vk(a.alternate, a, fj);
      a.memoizedProps = a.pendingProps;
      null === b ? Sk(a) : Y = b;
      nk.current = null;
    }
    function Sk(a) {
      var b = a;
      do {
        var c = b.alternate;
        a = b.return;
        if (0 === (b.flags & 32768)) {
          if (c = Ej(c, b, fj), null !== c) {
            Y = c;
            return;
          }
        } else {
          c = Ij(c, b);
          if (null !== c) {
            c.flags &= 32767;
            Y = c;
            return;
          }
          if (null !== a) a.flags |= 32768, a.subtreeFlags = 0, a.deletions = null;
          else {
            T = 6;
            Y = null;
            return;
          }
        }
        b = b.sibling;
        if (null !== b) {
          Y = b;
          return;
        }
        Y = b = a;
      } while (null !== b);
      0 === T && (T = 5);
    }
    function Pk(a, b, c) {
      var d = C, e = ok.transition;
      try {
        ok.transition = null, C = 1, Wk(a, b, c, d);
      } finally {
        ok.transition = e, C = d;
      }
      return null;
    }
    function Wk(a, b, c, d) {
      do
        Hk();
      while (null !== wk);
      if (0 !== (K & 6)) throw Error(p(327));
      c = a.finishedWork;
      var e = a.finishedLanes;
      if (null === c) return null;
      a.finishedWork = null;
      a.finishedLanes = 0;
      if (c === a.current) throw Error(p(177));
      a.callbackNode = null;
      a.callbackPriority = 0;
      var f = c.lanes | c.childLanes;
      Bc(a, f);
      a === Q && (Y = Q = null, Z = 0);
      0 === (c.subtreeFlags & 2064) && 0 === (c.flags & 2064) || vk || (vk = true, Fk(hc, function() {
        Hk();
        return null;
      }));
      f = 0 !== (c.flags & 15990);
      if (0 !== (c.subtreeFlags & 15990) || f) {
        f = ok.transition;
        ok.transition = null;
        var g = C;
        C = 1;
        var h = K;
        K |= 4;
        nk.current = null;
        Oj(a, c);
        dk(c, a);
        Oe(Df);
        dd = !!Cf;
        Df = Cf = null;
        a.current = c;
        hk(c);
        dc();
        K = h;
        C = g;
        ok.transition = f;
      } else a.current = c;
      vk && (vk = false, wk = a, xk = e);
      f = a.pendingLanes;
      0 === f && (Ri = null);
      mc(c.stateNode);
      Dk(a, B());
      if (null !== b) for (d = a.onRecoverableError, c = 0; c < b.length; c++) e = b[c], d(e.value, { componentStack: e.stack, digest: e.digest });
      if (Oi) throw Oi = false, a = Pi, Pi = null, a;
      0 !== (xk & 1) && 0 !== a.tag && Hk();
      f = a.pendingLanes;
      0 !== (f & 1) ? a === zk ? yk++ : (yk = 0, zk = a) : yk = 0;
      jg();
      return null;
    }
    function Hk() {
      if (null !== wk) {
        var a = Dc(xk), b = ok.transition, c = C;
        try {
          ok.transition = null;
          C = 16 > a ? 16 : a;
          if (null === wk) var d = false;
          else {
            a = wk;
            wk = null;
            xk = 0;
            if (0 !== (K & 6)) throw Error(p(331));
            var e = K;
            K |= 4;
            for (V = a.current; null !== V; ) {
              var f = V, g = f.child;
              if (0 !== (V.flags & 16)) {
                var h = f.deletions;
                if (null !== h) {
                  for (var k = 0; k < h.length; k++) {
                    var l = h[k];
                    for (V = l; null !== V; ) {
                      var m = V;
                      switch (m.tag) {
                        case 0:
                        case 11:
                        case 15:
                          Pj(8, m, f);
                      }
                      var q = m.child;
                      if (null !== q) q.return = m, V = q;
                      else for (; null !== V; ) {
                        m = V;
                        var r = m.sibling, y = m.return;
                        Sj(m);
                        if (m === l) {
                          V = null;
                          break;
                        }
                        if (null !== r) {
                          r.return = y;
                          V = r;
                          break;
                        }
                        V = y;
                      }
                    }
                  }
                  var n = f.alternate;
                  if (null !== n) {
                    var t = n.child;
                    if (null !== t) {
                      n.child = null;
                      do {
                        var J = t.sibling;
                        t.sibling = null;
                        t = J;
                      } while (null !== t);
                    }
                  }
                  V = f;
                }
              }
              if (0 !== (f.subtreeFlags & 2064) && null !== g) g.return = f, V = g;
              else b: for (; null !== V; ) {
                f = V;
                if (0 !== (f.flags & 2048)) switch (f.tag) {
                  case 0:
                  case 11:
                  case 15:
                    Pj(9, f, f.return);
                }
                var x = f.sibling;
                if (null !== x) {
                  x.return = f.return;
                  V = x;
                  break b;
                }
                V = f.return;
              }
            }
            var w = a.current;
            for (V = w; null !== V; ) {
              g = V;
              var u = g.child;
              if (0 !== (g.subtreeFlags & 2064) && null !== u) u.return = g, V = u;
              else b: for (g = w; null !== V; ) {
                h = V;
                if (0 !== (h.flags & 2048)) try {
                  switch (h.tag) {
                    case 0:
                    case 11:
                    case 15:
                      Qj(9, h);
                  }
                } catch (na) {
                  W(h, h.return, na);
                }
                if (h === g) {
                  V = null;
                  break b;
                }
                var F = h.sibling;
                if (null !== F) {
                  F.return = h.return;
                  V = F;
                  break b;
                }
                V = h.return;
              }
            }
            K = e;
            jg();
            if (lc && "function" === typeof lc.onPostCommitFiberRoot) try {
              lc.onPostCommitFiberRoot(kc, a);
            } catch (na) {
            }
            d = true;
          }
          return d;
        } finally {
          C = c, ok.transition = b;
        }
      }
      return false;
    }
    function Xk(a, b, c) {
      b = Ji(c, b);
      b = Ni(a, b, 1);
      a = nh(a, b, 1);
      b = R();
      null !== a && (Ac(a, 1, b), Dk(a, b));
    }
    function W(a, b, c) {
      if (3 === a.tag) Xk(a, a, c);
      else for (; null !== b; ) {
        if (3 === b.tag) {
          Xk(b, a, c);
          break;
        } else if (1 === b.tag) {
          var d = b.stateNode;
          if ("function" === typeof b.type.getDerivedStateFromError || "function" === typeof d.componentDidCatch && (null === Ri || !Ri.has(d))) {
            a = Ji(c, a);
            a = Qi(b, a, 1);
            b = nh(b, a, 1);
            a = R();
            null !== b && (Ac(b, 1, a), Dk(b, a));
            break;
          }
        }
        b = b.return;
      }
    }
    function Ti(a, b, c) {
      var d = a.pingCache;
      null !== d && d.delete(b);
      b = R();
      a.pingedLanes |= a.suspendedLanes & c;
      Q === a && (Z & c) === c && (4 === T || 3 === T && (Z & 130023424) === Z && 500 > B() - fk ? Kk(a, 0) : rk |= c);
      Dk(a, b);
    }
    function Yk(a, b) {
      0 === b && (0 === (a.mode & 1) ? b = 1 : (b = sc, sc <<= 1, 0 === (sc & 130023424) && (sc = 4194304)));
      var c = R();
      a = ih(a, b);
      null !== a && (Ac(a, b, c), Dk(a, c));
    }
    function uj(a) {
      var b = a.memoizedState, c = 0;
      null !== b && (c = b.retryLane);
      Yk(a, c);
    }
    function bk(a, b) {
      var c = 0;
      switch (a.tag) {
        case 13:
          var d = a.stateNode;
          var e = a.memoizedState;
          null !== e && (c = e.retryLane);
          break;
        case 19:
          d = a.stateNode;
          break;
        default:
          throw Error(p(314));
      }
      null !== d && d.delete(b);
      Yk(a, c);
    }
    var Vk;
    Vk = function(a, b, c) {
      if (null !== a) if (a.memoizedProps !== b.pendingProps || Wf.current) dh = true;
      else {
        if (0 === (a.lanes & c) && 0 === (b.flags & 128)) return dh = false, yj(a, b, c);
        dh = 0 !== (a.flags & 131072) ? true : false;
      }
      else dh = false, I && 0 !== (b.flags & 1048576) && ug(b, ng, b.index);
      b.lanes = 0;
      switch (b.tag) {
        case 2:
          var d = b.type;
          ij(a, b);
          a = b.pendingProps;
          var e = Yf(b, H.current);
          ch(b, c);
          e = Nh(null, b, d, a, e, c);
          var f = Sh();
          b.flags |= 1;
          "object" === typeof e && null !== e && "function" === typeof e.render && void 0 === e.$$typeof ? (b.tag = 1, b.memoizedState = null, b.updateQueue = null, Zf(d) ? (f = true, cg(b)) : f = false, b.memoizedState = null !== e.state && void 0 !== e.state ? e.state : null, kh(b), e.updater = Ei, b.stateNode = e, e._reactInternals = b, Ii(b, d, a, c), b = jj(null, b, d, true, f, c)) : (b.tag = 0, I && f && vg(b), Xi(null, b, e, c), b = b.child);
          return b;
        case 16:
          d = b.elementType;
          a: {
            ij(a, b);
            a = b.pendingProps;
            e = d._init;
            d = e(d._payload);
            b.type = d;
            e = b.tag = Zk(d);
            a = Ci(d, a);
            switch (e) {
              case 0:
                b = cj(null, b, d, a, c);
                break a;
              case 1:
                b = hj(null, b, d, a, c);
                break a;
              case 11:
                b = Yi(null, b, d, a, c);
                break a;
              case 14:
                b = $i(null, b, d, Ci(d.type, a), c);
                break a;
            }
            throw Error(p(
              306,
              d,
              ""
            ));
          }
          return b;
        case 0:
          return d = b.type, e = b.pendingProps, e = b.elementType === d ? e : Ci(d, e), cj(a, b, d, e, c);
        case 1:
          return d = b.type, e = b.pendingProps, e = b.elementType === d ? e : Ci(d, e), hj(a, b, d, e, c);
        case 3:
          a: {
            kj(b);
            if (null === a) throw Error(p(387));
            d = b.pendingProps;
            f = b.memoizedState;
            e = f.element;
            lh(a, b);
            qh(b, d, null, c);
            var g = b.memoizedState;
            d = g.element;
            if (f.isDehydrated) if (f = { element: d, isDehydrated: false, cache: g.cache, pendingSuspenseBoundaries: g.pendingSuspenseBoundaries, transitions: g.transitions }, b.updateQueue.baseState = f, b.memoizedState = f, b.flags & 256) {
              e = Ji(Error(p(423)), b);
              b = lj(a, b, d, c, e);
              break a;
            } else if (d !== e) {
              e = Ji(Error(p(424)), b);
              b = lj(a, b, d, c, e);
              break a;
            } else for (yg = Lf(b.stateNode.containerInfo.firstChild), xg = b, I = true, zg = null, c = Vg(b, null, d, c), b.child = c; c; ) c.flags = c.flags & -3 | 4096, c = c.sibling;
            else {
              Ig();
              if (d === e) {
                b = Zi(a, b, c);
                break a;
              }
              Xi(a, b, d, c);
            }
            b = b.child;
          }
          return b;
        case 5:
          return Ah(b), null === a && Eg(b), d = b.type, e = b.pendingProps, f = null !== a ? a.memoizedProps : null, g = e.children, Ef(d, e) ? g = null : null !== f && Ef(d, f) && (b.flags |= 32), gj(a, b), Xi(a, b, g, c), b.child;
        case 6:
          return null === a && Eg(b), null;
        case 13:
          return oj(a, b, c);
        case 4:
          return yh(b, b.stateNode.containerInfo), d = b.pendingProps, null === a ? b.child = Ug(b, null, d, c) : Xi(a, b, d, c), b.child;
        case 11:
          return d = b.type, e = b.pendingProps, e = b.elementType === d ? e : Ci(d, e), Yi(a, b, d, e, c);
        case 7:
          return Xi(a, b, b.pendingProps, c), b.child;
        case 8:
          return Xi(a, b, b.pendingProps.children, c), b.child;
        case 12:
          return Xi(a, b, b.pendingProps.children, c), b.child;
        case 10:
          a: {
            d = b.type._context;
            e = b.pendingProps;
            f = b.memoizedProps;
            g = e.value;
            G(Wg, d._currentValue);
            d._currentValue = g;
            if (null !== f) if (He(f.value, g)) {
              if (f.children === e.children && !Wf.current) {
                b = Zi(a, b, c);
                break a;
              }
            } else for (f = b.child, null !== f && (f.return = b); null !== f; ) {
              var h = f.dependencies;
              if (null !== h) {
                g = f.child;
                for (var k = h.firstContext; null !== k; ) {
                  if (k.context === d) {
                    if (1 === f.tag) {
                      k = mh(-1, c & -c);
                      k.tag = 2;
                      var l = f.updateQueue;
                      if (null !== l) {
                        l = l.shared;
                        var m = l.pending;
                        null === m ? k.next = k : (k.next = m.next, m.next = k);
                        l.pending = k;
                      }
                    }
                    f.lanes |= c;
                    k = f.alternate;
                    null !== k && (k.lanes |= c);
                    bh(
                      f.return,
                      c,
                      b
                    );
                    h.lanes |= c;
                    break;
                  }
                  k = k.next;
                }
              } else if (10 === f.tag) g = f.type === b.type ? null : f.child;
              else if (18 === f.tag) {
                g = f.return;
                if (null === g) throw Error(p(341));
                g.lanes |= c;
                h = g.alternate;
                null !== h && (h.lanes |= c);
                bh(g, c, b);
                g = f.sibling;
              } else g = f.child;
              if (null !== g) g.return = f;
              else for (g = f; null !== g; ) {
                if (g === b) {
                  g = null;
                  break;
                }
                f = g.sibling;
                if (null !== f) {
                  f.return = g.return;
                  g = f;
                  break;
                }
                g = g.return;
              }
              f = g;
            }
            Xi(a, b, e.children, c);
            b = b.child;
          }
          return b;
        case 9:
          return e = b.type, d = b.pendingProps.children, ch(b, c), e = eh(e), d = d(e), b.flags |= 1, Xi(a, b, d, c), b.child;
        case 14:
          return d = b.type, e = Ci(d, b.pendingProps), e = Ci(d.type, e), $i(a, b, d, e, c);
        case 15:
          return bj(a, b, b.type, b.pendingProps, c);
        case 17:
          return d = b.type, e = b.pendingProps, e = b.elementType === d ? e : Ci(d, e), ij(a, b), b.tag = 1, Zf(d) ? (a = true, cg(b)) : a = false, ch(b, c), Gi(b, d, e), Ii(b, d, e, c), jj(null, b, d, true, a, c);
        case 19:
          return xj(a, b, c);
        case 22:
          return dj(a, b, c);
      }
      throw Error(p(156, b.tag));
    };
    function Fk(a, b) {
      return ac(a, b);
    }
    function $k(a, b, c, d) {
      this.tag = a;
      this.key = c;
      this.sibling = this.child = this.return = this.stateNode = this.type = this.elementType = null;
      this.index = 0;
      this.ref = null;
      this.pendingProps = b;
      this.dependencies = this.memoizedState = this.updateQueue = this.memoizedProps = null;
      this.mode = d;
      this.subtreeFlags = this.flags = 0;
      this.deletions = null;
      this.childLanes = this.lanes = 0;
      this.alternate = null;
    }
    function Bg(a, b, c, d) {
      return new $k(a, b, c, d);
    }
    function aj(a) {
      a = a.prototype;
      return !(!a || !a.isReactComponent);
    }
    function Zk(a) {
      if ("function" === typeof a) return aj(a) ? 1 : 0;
      if (void 0 !== a && null !== a) {
        a = a.$$typeof;
        if (a === Da) return 11;
        if (a === Ga) return 14;
      }
      return 2;
    }
    function Pg(a, b) {
      var c = a.alternate;
      null === c ? (c = Bg(a.tag, b, a.key, a.mode), c.elementType = a.elementType, c.type = a.type, c.stateNode = a.stateNode, c.alternate = a, a.alternate = c) : (c.pendingProps = b, c.type = a.type, c.flags = 0, c.subtreeFlags = 0, c.deletions = null);
      c.flags = a.flags & 14680064;
      c.childLanes = a.childLanes;
      c.lanes = a.lanes;
      c.child = a.child;
      c.memoizedProps = a.memoizedProps;
      c.memoizedState = a.memoizedState;
      c.updateQueue = a.updateQueue;
      b = a.dependencies;
      c.dependencies = null === b ? null : { lanes: b.lanes, firstContext: b.firstContext };
      c.sibling = a.sibling;
      c.index = a.index;
      c.ref = a.ref;
      return c;
    }
    function Rg(a, b, c, d, e, f) {
      var g = 2;
      d = a;
      if ("function" === typeof a) aj(a) && (g = 1);
      else if ("string" === typeof a) g = 5;
      else a: switch (a) {
        case ya:
          return Tg(c.children, e, f, b);
        case za:
          g = 8;
          e |= 8;
          break;
        case Aa:
          return a = Bg(12, c, b, e | 2), a.elementType = Aa, a.lanes = f, a;
        case Ea:
          return a = Bg(13, c, b, e), a.elementType = Ea, a.lanes = f, a;
        case Fa:
          return a = Bg(19, c, b, e), a.elementType = Fa, a.lanes = f, a;
        case Ia:
          return pj(c, e, f, b);
        default:
          if ("object" === typeof a && null !== a) switch (a.$$typeof) {
            case Ba:
              g = 10;
              break a;
            case Ca:
              g = 9;
              break a;
            case Da:
              g = 11;
              break a;
            case Ga:
              g = 14;
              break a;
            case Ha:
              g = 16;
              d = null;
              break a;
          }
          throw Error(p(130, null == a ? a : typeof a, ""));
      }
      b = Bg(g, c, b, e);
      b.elementType = a;
      b.type = d;
      b.lanes = f;
      return b;
    }
    function Tg(a, b, c, d) {
      a = Bg(7, a, d, b);
      a.lanes = c;
      return a;
    }
    function pj(a, b, c, d) {
      a = Bg(22, a, d, b);
      a.elementType = Ia;
      a.lanes = c;
      a.stateNode = { isHidden: false };
      return a;
    }
    function Qg(a, b, c) {
      a = Bg(6, a, null, b);
      a.lanes = c;
      return a;
    }
    function Sg(a, b, c) {
      b = Bg(4, null !== a.children ? a.children : [], a.key, b);
      b.lanes = c;
      b.stateNode = { containerInfo: a.containerInfo, pendingChildren: null, implementation: a.implementation };
      return b;
    }
    function al(a, b, c, d, e) {
      this.tag = b;
      this.containerInfo = a;
      this.finishedWork = this.pingCache = this.current = this.pendingChildren = null;
      this.timeoutHandle = -1;
      this.callbackNode = this.pendingContext = this.context = null;
      this.callbackPriority = 0;
      this.eventTimes = zc(0);
      this.expirationTimes = zc(-1);
      this.entangledLanes = this.finishedLanes = this.mutableReadLanes = this.expiredLanes = this.pingedLanes = this.suspendedLanes = this.pendingLanes = 0;
      this.entanglements = zc(0);
      this.identifierPrefix = d;
      this.onRecoverableError = e;
      this.mutableSourceEagerHydrationData = null;
    }
    function bl(a, b, c, d, e, f, g, h, k) {
      a = new al(a, b, c, h, k);
      1 === b ? (b = 1, true === f && (b |= 8)) : b = 0;
      f = Bg(3, null, null, b);
      a.current = f;
      f.stateNode = a;
      f.memoizedState = { element: d, isDehydrated: c, cache: null, transitions: null, pendingSuspenseBoundaries: null };
      kh(f);
      return a;
    }
    function cl(a, b, c) {
      var d = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null;
      return { $$typeof: wa, key: null == d ? null : "" + d, children: a, containerInfo: b, implementation: c };
    }
    function dl(a) {
      if (!a) return Vf;
      a = a._reactInternals;
      a: {
        if (Vb(a) !== a || 1 !== a.tag) throw Error(p(170));
        var b = a;
        do {
          switch (b.tag) {
            case 3:
              b = b.stateNode.context;
              break a;
            case 1:
              if (Zf(b.type)) {
                b = b.stateNode.__reactInternalMemoizedMergedChildContext;
                break a;
              }
          }
          b = b.return;
        } while (null !== b);
        throw Error(p(171));
      }
      if (1 === a.tag) {
        var c = a.type;
        if (Zf(c)) return bg(a, c, b);
      }
      return b;
    }
    function el(a, b, c, d, e, f, g, h, k) {
      a = bl(c, d, true, a, e, f, g, h, k);
      a.context = dl(null);
      c = a.current;
      d = R();
      e = yi(c);
      f = mh(d, e);
      f.callback = void 0 !== b && null !== b ? b : null;
      nh(c, f, e);
      a.current.lanes = e;
      Ac(a, e, d);
      Dk(a, d);
      return a;
    }
    function fl(a, b, c, d) {
      var e = b.current, f = R(), g = yi(e);
      c = dl(c);
      null === b.context ? b.context = c : b.pendingContext = c;
      b = mh(f, g);
      b.payload = { element: a };
      d = void 0 === d ? null : d;
      null !== d && (b.callback = d);
      a = nh(e, b, g);
      null !== a && (gi(a, e, g, f), oh(a, e, g));
      return g;
    }
    function gl(a) {
      a = a.current;
      if (!a.child) return null;
      switch (a.child.tag) {
        case 5:
          return a.child.stateNode;
        default:
          return a.child.stateNode;
      }
    }
    function hl(a, b) {
      a = a.memoizedState;
      if (null !== a && null !== a.dehydrated) {
        var c = a.retryLane;
        a.retryLane = 0 !== c && c < b ? c : b;
      }
    }
    function il(a, b) {
      hl(a, b);
      (a = a.alternate) && hl(a, b);
    }
    function jl() {
      return null;
    }
    var kl = "function" === typeof reportError ? reportError : function(a) {
      console.error(a);
    };
    function ll(a) {
      this._internalRoot = a;
    }
    ml.prototype.render = ll.prototype.render = function(a) {
      var b = this._internalRoot;
      if (null === b) throw Error(p(409));
      fl(a, b, null, null);
    };
    ml.prototype.unmount = ll.prototype.unmount = function() {
      var a = this._internalRoot;
      if (null !== a) {
        this._internalRoot = null;
        var b = a.containerInfo;
        Rk(function() {
          fl(null, a, null, null);
        });
        b[uf] = null;
      }
    };
    function ml(a) {
      this._internalRoot = a;
    }
    ml.prototype.unstable_scheduleHydration = function(a) {
      if (a) {
        var b = Hc();
        a = { blockedOn: null, target: a, priority: b };
        for (var c = 0; c < Qc.length && 0 !== b && b < Qc[c].priority; c++) ;
        Qc.splice(c, 0, a);
        0 === c && Vc(a);
      }
    };
    function nl(a) {
      return !(!a || 1 !== a.nodeType && 9 !== a.nodeType && 11 !== a.nodeType);
    }
    function ol(a) {
      return !(!a || 1 !== a.nodeType && 9 !== a.nodeType && 11 !== a.nodeType && (8 !== a.nodeType || " react-mount-point-unstable " !== a.nodeValue));
    }
    function pl() {
    }
    function ql(a, b, c, d, e) {
      if (e) {
        if ("function" === typeof d) {
          var f = d;
          d = function() {
            var a2 = gl(g);
            f.call(a2);
          };
        }
        var g = el(b, d, a, 0, null, false, false, "", pl);
        a._reactRootContainer = g;
        a[uf] = g.current;
        sf(8 === a.nodeType ? a.parentNode : a);
        Rk();
        return g;
      }
      for (; e = a.lastChild; ) a.removeChild(e);
      if ("function" === typeof d) {
        var h = d;
        d = function() {
          var a2 = gl(k);
          h.call(a2);
        };
      }
      var k = bl(a, 0, false, null, null, false, false, "", pl);
      a._reactRootContainer = k;
      a[uf] = k.current;
      sf(8 === a.nodeType ? a.parentNode : a);
      Rk(function() {
        fl(b, k, c, d);
      });
      return k;
    }
    function rl(a, b, c, d, e) {
      var f = c._reactRootContainer;
      if (f) {
        var g = f;
        if ("function" === typeof e) {
          var h = e;
          e = function() {
            var a2 = gl(g);
            h.call(a2);
          };
        }
        fl(b, g, a, e);
      } else g = ql(c, b, a, e, d);
      return gl(g);
    }
    Ec = function(a) {
      switch (a.tag) {
        case 3:
          var b = a.stateNode;
          if (b.current.memoizedState.isDehydrated) {
            var c = tc(b.pendingLanes);
            0 !== c && (Cc(b, c | 1), Dk(b, B()), 0 === (K & 6) && (Gj = B() + 500, jg()));
          }
          break;
        case 13:
          Rk(function() {
            var b2 = ih(a, 1);
            if (null !== b2) {
              var c2 = R();
              gi(b2, a, 1, c2);
            }
          }), il(a, 1);
      }
    };
    Fc = function(a) {
      if (13 === a.tag) {
        var b = ih(a, 134217728);
        if (null !== b) {
          var c = R();
          gi(b, a, 134217728, c);
        }
        il(a, 134217728);
      }
    };
    Gc = function(a) {
      if (13 === a.tag) {
        var b = yi(a), c = ih(a, b);
        if (null !== c) {
          var d = R();
          gi(c, a, b, d);
        }
        il(a, b);
      }
    };
    Hc = function() {
      return C;
    };
    Ic = function(a, b) {
      var c = C;
      try {
        return C = a, b();
      } finally {
        C = c;
      }
    };
    yb = function(a, b, c) {
      switch (b) {
        case "input":
          bb(a, c);
          b = c.name;
          if ("radio" === c.type && null != b) {
            for (c = a; c.parentNode; ) c = c.parentNode;
            c = c.querySelectorAll("input[name=" + JSON.stringify("" + b) + '][type="radio"]');
            for (b = 0; b < c.length; b++) {
              var d = c[b];
              if (d !== a && d.form === a.form) {
                var e = Db(d);
                if (!e) throw Error(p(90));
                Wa(d);
                bb(d, e);
              }
            }
          }
          break;
        case "textarea":
          ib(a, c);
          break;
        case "select":
          b = c.value, null != b && fb(a, !!c.multiple, b, false);
      }
    };
    Gb = Qk;
    Hb = Rk;
    var sl = { usingClientEntryPoint: false, Events: [Cb, ue, Db, Eb, Fb, Qk] }, tl = { findFiberByHostInstance: Wc, bundleType: 0, version: "18.3.1", rendererPackageName: "react-dom" };
    var ul = { bundleType: tl.bundleType, version: tl.version, rendererPackageName: tl.rendererPackageName, rendererConfig: tl.rendererConfig, overrideHookState: null, overrideHookStateDeletePath: null, overrideHookStateRenamePath: null, overrideProps: null, overridePropsDeletePath: null, overridePropsRenamePath: null, setErrorHandler: null, setSuspenseHandler: null, scheduleUpdate: null, currentDispatcherRef: ua.ReactCurrentDispatcher, findHostInstanceByFiber: function(a) {
      a = Zb(a);
      return null === a ? null : a.stateNode;
    }, findFiberByHostInstance: tl.findFiberByHostInstance || jl, findHostInstancesForRefresh: null, scheduleRefresh: null, scheduleRoot: null, setRefreshHandler: null, getCurrentFiber: null, reconcilerVersion: "18.3.1-next-f1338f8080-20240426" };
    if ("undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__) {
      var vl = __REACT_DEVTOOLS_GLOBAL_HOOK__;
      if (!vl.isDisabled && vl.supportsFiber) try {
        kc = vl.inject(ul), lc = vl;
      } catch (a) {
      }
    }
    reactDom_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = sl;
    reactDom_production_min.createPortal = function(a, b) {
      var c = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null;
      if (!nl(b)) throw Error(p(200));
      return cl(a, b, null, c);
    };
    reactDom_production_min.createRoot = function(a, b) {
      if (!nl(a)) throw Error(p(299));
      var c = false, d = "", e = kl;
      null !== b && void 0 !== b && (true === b.unstable_strictMode && (c = true), void 0 !== b.identifierPrefix && (d = b.identifierPrefix), void 0 !== b.onRecoverableError && (e = b.onRecoverableError));
      b = bl(a, 1, false, null, null, c, false, d, e);
      a[uf] = b.current;
      sf(8 === a.nodeType ? a.parentNode : a);
      return new ll(b);
    };
    reactDom_production_min.findDOMNode = function(a) {
      if (null == a) return null;
      if (1 === a.nodeType) return a;
      var b = a._reactInternals;
      if (void 0 === b) {
        if ("function" === typeof a.render) throw Error(p(188));
        a = Object.keys(a).join(",");
        throw Error(p(268, a));
      }
      a = Zb(b);
      a = null === a ? null : a.stateNode;
      return a;
    };
    reactDom_production_min.flushSync = function(a) {
      return Rk(a);
    };
    reactDom_production_min.hydrate = function(a, b, c) {
      if (!ol(b)) throw Error(p(200));
      return rl(null, a, b, true, c);
    };
    reactDom_production_min.hydrateRoot = function(a, b, c) {
      if (!nl(a)) throw Error(p(405));
      var d = null != c && c.hydratedSources || null, e = false, f = "", g = kl;
      null !== c && void 0 !== c && (true === c.unstable_strictMode && (e = true), void 0 !== c.identifierPrefix && (f = c.identifierPrefix), void 0 !== c.onRecoverableError && (g = c.onRecoverableError));
      b = el(b, null, a, 1, null != c ? c : null, e, false, f, g);
      a[uf] = b.current;
      sf(a);
      if (d) for (a = 0; a < d.length; a++) c = d[a], e = c._getVersion, e = e(c._source), null == b.mutableSourceEagerHydrationData ? b.mutableSourceEagerHydrationData = [c, e] : b.mutableSourceEagerHydrationData.push(
        c,
        e
      );
      return new ml(b);
    };
    reactDom_production_min.render = function(a, b, c) {
      if (!ol(b)) throw Error(p(200));
      return rl(null, a, b, false, c);
    };
    reactDom_production_min.unmountComponentAtNode = function(a) {
      if (!ol(a)) throw Error(p(40));
      return a._reactRootContainer ? (Rk(function() {
        rl(null, null, a, false, function() {
          a._reactRootContainer = null;
          a[uf] = null;
        });
      }), true) : false;
    };
    reactDom_production_min.unstable_batchedUpdates = Qk;
    reactDom_production_min.unstable_renderSubtreeIntoContainer = function(a, b, c, d) {
      if (!ol(c)) throw Error(p(200));
      if (null == a || void 0 === a._reactInternals) throw Error(p(38));
      return rl(a, b, c, false, d);
    };
    reactDom_production_min.version = "18.3.1-next-f1338f8080-20240426";
    return reactDom_production_min;
  }
  var hasRequiredReactDom;
  function requireReactDom() {
    if (hasRequiredReactDom) return reactDom.exports;
    hasRequiredReactDom = 1;
    function checkDCE() {
      if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined" || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== "function") {
        return;
      }
      try {
        __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
      } catch (err) {
        console.error(err);
      }
    }
    {
      checkDCE();
      reactDom.exports = requireReactDom_production_min();
    }
    return reactDom.exports;
  }
  var hasRequiredClient;
  function requireClient() {
    if (hasRequiredClient) return client$1;
    hasRequiredClient = 1;
    var m = requireReactDom();
    {
      client$1.createRoot = m.createRoot;
      client$1.hydrateRoot = m.hydrateRoot;
    }
    return client$1;
  }
  var clientExports = requireClient();
  var reactExports = requireReact();
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const mergeClasses = (...classes) => classes.filter((className, index, array) => {
    return Boolean(className) && className.trim() !== "" && array.indexOf(className) === index;
  }).join(" ").trim();
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const toKebabCase = (string) => string.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const toCamelCase = (string) => string.replace(
    /^([A-Z])|[\s-_]+(\w)/g,
    (match, p1, p2) => p2 ? p2.toUpperCase() : p1.toLowerCase()
  );
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const toPascalCase = (string) => {
    const camelCase = toCamelCase(string);
    return camelCase.charAt(0).toUpperCase() + camelCase.slice(1);
  };
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  var defaultAttributes = {
    xmlns: "http://www.w3.org/2000/svg",
    width: 24,
    height: 24,
    viewBox: "0 0 24 24",
    fill: "none",
    stroke: "currentColor",
    strokeWidth: 2,
    strokeLinecap: "round",
    strokeLinejoin: "round"
  };
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const hasA11yProp = (props) => {
    for (const prop in props) {
      if (prop.startsWith("aria-") || prop === "role" || prop === "title") {
        return true;
      }
    }
    return false;
  };
  const LucideContext = reactExports.createContext({});
  const useLucideContext = () => reactExports.useContext(LucideContext);
  const Icon = reactExports.forwardRef(
    ({ color: color2, size, strokeWidth, absoluteStrokeWidth, className = "", children, iconNode, ...rest }, ref) => {
      const {
        size: contextSize = 24,
        strokeWidth: contextStrokeWidth = 2,
        absoluteStrokeWidth: contextAbsoluteStrokeWidth = false,
        color: contextColor = "currentColor",
        className: contextClass = ""
      } = useLucideContext() ?? {};
      const calculatedStrokeWidth = absoluteStrokeWidth ?? contextAbsoluteStrokeWidth ? Number(strokeWidth ?? contextStrokeWidth) * 24 / Number(size ?? contextSize) : strokeWidth ?? contextStrokeWidth;
      return reactExports.createElement(
        "svg",
        {
          ref,
          ...defaultAttributes,
          width: size ?? contextSize ?? defaultAttributes.width,
          height: size ?? contextSize ?? defaultAttributes.height,
          stroke: color2 ?? contextColor,
          strokeWidth: calculatedStrokeWidth,
          className: mergeClasses("lucide", contextClass, className),
          ...!children && !hasA11yProp(rest) && { "aria-hidden": "true" },
          ...rest
        },
        [
          ...iconNode.map(([tag, attrs]) => reactExports.createElement(tag, attrs)),
          ...Array.isArray(children) ? children : [children]
        ]
      );
    }
  );
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const createLucideIcon = (iconName, iconNode) => {
    const Component = reactExports.forwardRef(
      ({ className, ...props }, ref) => reactExports.createElement(Icon, {
        ref,
        iconNode,
        className: mergeClasses(
          `lucide-${toKebabCase(toPascalCase(iconName))}`,
          `lucide-${iconName}`,
          className
        ),
        ...props
      })
    );
    Component.displayName = toPascalCase(iconName);
    return Component;
  };
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$l = [
    ["path", { d: "M10.268 21a2 2 0 0 0 3.464 0", key: "vwvbt9" }],
    [
      "path",
      {
        d: "M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",
        key: "11g9vi"
      }
    ]
  ];
  const Bell = createLucideIcon("bell", __iconNode$l);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$k = [
    ["path", { d: "M10 12h4", key: "a56b0p" }],
    ["path", { d: "M10 8h4", key: "1sr2af" }],
    ["path", { d: "M14 21v-3a2 2 0 0 0-4 0v3", key: "1rgiei" }],
    [
      "path",
      {
        d: "M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2",
        key: "secmi2"
      }
    ],
    ["path", { d: "M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16", key: "16ra0t" }]
  ];
  const Building2 = createLucideIcon("building-2", __iconNode$k);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$j = [["path", { d: "m9 18 6-6-6-6", key: "mthhwq" }]];
  const ChevronRight = createLucideIcon("chevron-right", __iconNode$j);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$i = [
    ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
    ["line", { x1: "10", x2: "10", y1: "15", y2: "9", key: "c1nkhi" }],
    ["line", { x1: "14", x2: "14", y1: "15", y2: "9", key: "h65svq" }]
  ];
  const CirclePause = createLucideIcon("circle-pause", __iconNode$i);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$h = [
    [
      "path",
      {
        d: "M9 9.003a1 1 0 0 1 1.517-.859l4.997 2.997a1 1 0 0 1 0 1.718l-4.997 2.997A1 1 0 0 1 9 14.996z",
        key: "kmsa83"
      }
    ],
    ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }]
  ];
  const CirclePlay = createLucideIcon("circle-play", __iconNode$h);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$g = [
    ["rect", { width: "14", height: "14", x: "8", y: "8", rx: "2", ry: "2", key: "17jyea" }],
    ["path", { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2", key: "zix9uf" }]
  ];
  const Copy = createLucideIcon("copy", __iconNode$g);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$f = [
    ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
    ["line", { x1: "22", x2: "18", y1: "12", y2: "12", key: "l9bcsi" }],
    ["line", { x1: "6", x2: "2", y1: "12", y2: "12", key: "13hhkx" }],
    ["line", { x1: "12", x2: "12", y1: "6", y2: "2", key: "10w3f3" }],
    ["line", { x1: "12", x2: "12", y1: "22", y2: "18", key: "15g9kq" }]
  ];
  const Crosshair = createLucideIcon("crosshair", __iconNode$f);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$e = [
    ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }],
    ["path", { d: "M16 16s-1.5-2-4-2-4 2-4 2", key: "epbg0q" }],
    ["line", { x1: "9", x2: "9.01", y1: "9", y2: "9", key: "yxxnd0" }],
    ["line", { x1: "15", x2: "15.01", y1: "9", y2: "9", key: "1p4y9e" }]
  ];
  const Frown = createLucideIcon("frown", __iconNode$e);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$d = [
    ["path", { d: "M11 15h2a2 2 0 1 0 0-4h-3c-.6 0-1.1.2-1.4.6L3 17", key: "geh8rc" }],
    [
      "path",
      {
        d: "m7 21 1.6-1.4c.3-.4.8-.6 1.4-.6h4c1.1 0 2.1-.4 2.8-1.2l4.6-4.4a2 2 0 0 0-2.75-2.91l-4.2 3.9",
        key: "1fto5m"
      }
    ],
    ["path", { d: "m2 16 6 6", key: "1pfhp9" }],
    ["circle", { cx: "16", cy: "9", r: "2.9", key: "1n0dlu" }],
    ["circle", { cx: "6", cy: "5", r: "3", key: "151irh" }]
  ];
  const HandCoins = createLucideIcon("hand-coins", __iconNode$d);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$c = [
    ["path", { d: "m11 17 2 2a1 1 0 1 0 3-3", key: "efffak" }],
    [
      "path",
      {
        d: "m14 14 2.5 2.5a1 1 0 1 0 3-3l-3.88-3.88a3 3 0 0 0-4.24 0l-.88.88a1 1 0 1 1-3-3l2.81-2.81a5.79 5.79 0 0 1 7.06-.87l.47.28a2 2 0 0 0 1.42.25L21 4",
        key: "9pr0kb"
      }
    ],
    ["path", { d: "m21 3 1 11h-2", key: "1tisrp" }],
    ["path", { d: "M3 3 2 14l6.5 6.5a1 1 0 1 0 3-3", key: "1uvwmv" }],
    ["path", { d: "M3 4h8", key: "1ep09j" }]
  ];
  const Handshake = createLucideIcon("handshake", __iconNode$c);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$b = [
    ["path", { d: "M14 18a2 2 0 0 0-4 0", key: "1v8fkw" }],
    [
      "path",
      {
        d: "m19 11-2.11-6.657a2 2 0 0 0-2.752-1.148l-1.276.61A2 2 0 0 1 12 4H8.5a2 2 0 0 0-1.925 1.456L5 11",
        key: "1fkr7p"
      }
    ],
    ["path", { d: "M2 11h20", key: "3eubbj" }],
    ["circle", { cx: "17", cy: "18", r: "3", key: "82mm0e" }],
    ["circle", { cx: "7", cy: "18", r: "3", key: "lvkj7j" }]
  ];
  const HatGlasses = createLucideIcon("hat-glasses", __iconNode$b);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$a = [
    ["line", { x1: "2", x2: "5", y1: "12", y2: "12", key: "bvdh0s" }],
    ["line", { x1: "19", x2: "22", y1: "12", y2: "12", key: "1tbv5k" }],
    ["line", { x1: "12", x2: "12", y1: "2", y2: "5", key: "11lu5j" }],
    ["line", { x1: "12", x2: "12", y1: "19", y2: "22", key: "x3vr5v" }],
    ["circle", { cx: "12", cy: "12", r: "7", key: "fim9np" }]
  ];
  const Locate = createLucideIcon("locate", __iconNode$a);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$9 = [
    [
      "path",
      { d: "m10.5 20.5 10-10a4.95 4.95 0 1 0-7-7l-10 10a4.95 4.95 0 1 0 7 7Z", key: "wa1lgi" }
    ],
    ["path", { d: "m8.5 8.5 7 7", key: "rvfmvr" }]
  ];
  const Pill = createLucideIcon("pill", __iconNode$9);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$8 = [
    ["path", { d: "M2 22h20", key: "272qi7" }],
    [
      "path",
      {
        d: "M6.36 17.4 4 17l-2-4 1.1-.55a2 2 0 0 1 1.8 0l.17.1a2 2 0 0 0 1.8 0L8 12 5 6l.9-.45a2 2 0 0 1 2.09.2l4.02 3a2 2 0 0 0 2.1.2l4.19-2.06a2.41 2.41 0 0 1 1.73-.17L21 7a1.4 1.4 0 0 1 .87 1.99l-.38.76c-.23.46-.6.84-1.07 1.08L7.58 17.2a2 2 0 0 1-1.22.18Z",
        key: "fkigj9"
      }
    ]
  ];
  const PlaneTakeoff = createLucideIcon("plane-takeoff", __iconNode$8);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$7 = [
    ["path", { d: "m21 21-4.34-4.34", key: "14j7rj" }],
    ["circle", { cx: "11", cy: "11", r: "8", key: "4ej97u" }]
  ];
  const Search = createLucideIcon("search", __iconNode$7);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$6 = [
    [
      "path",
      {
        d: "M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",
        key: "oel41y"
      }
    ]
  ];
  const Shield = createLucideIcon("shield", __iconNode$6);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$5 = [
    [
      "path",
      {
        d: "M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",
        key: "oel41y"
      }
    ],
    ["path", { d: "M6.376 18.91a6 6 0 0 1 11.249.003", key: "hnjrf2" }],
    ["circle", { cx: "12", cy: "11", r: "4", key: "1gt34v" }]
  ];
  const ShieldUser = createLucideIcon("shield-user", __iconNode$5);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$4 = [
    ["path", { d: "m12.5 17-.5-1-.5 1h1z", key: "3me087" }],
    [
      "path",
      {
        d: "M15 22a1 1 0 0 0 1-1v-1a2 2 0 0 0 1.56-3.25 8 8 0 1 0-11.12 0A2 2 0 0 0 8 20v1a1 1 0 0 0 1 1z",
        key: "1o5pge"
      }
    ],
    ["circle", { cx: "15", cy: "12", r: "1", key: "1tmaij" }],
    ["circle", { cx: "9", cy: "12", r: "1", key: "1vctgf" }]
  ];
  const Skull = createLucideIcon("skull", __iconNode$4);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$3 = [
    ["polyline", { points: "14.5 17.5 3 6 3 3 6 3 17.5 14.5", key: "1hfsw2" }],
    ["line", { x1: "13", x2: "19", y1: "19", y2: "13", key: "1vrmhu" }],
    ["line", { x1: "16", x2: "20", y1: "16", y2: "20", key: "1bron3" }],
    ["line", { x1: "19", x2: "21", y1: "21", y2: "19", key: "13pww6" }],
    ["polyline", { points: "14.5 6.5 18 3 21 3 21 6 17.5 9.5", key: "hbey2j" }],
    ["line", { x1: "5", x2: "9", y1: "14", y2: "18", key: "1hf58s" }],
    ["line", { x1: "7", x2: "4", y1: "17", y2: "20", key: "pidxm4" }],
    ["line", { x1: "3", x2: "5", y1: "19", y2: "21", key: "1pehsh" }]
  ];
  const Swords = createLucideIcon("swords", __iconNode$3);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$2 = [
    ["path", { d: "m16 11 2 2 4-4", key: "9rsbq5" }],
    ["path", { d: "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2", key: "1yyitq" }],
    ["circle", { cx: "9", cy: "7", r: "4", key: "nufk8" }]
  ];
  const UserCheck = createLucideIcon("user-check", __iconNode$2);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode$1 = [
    ["circle", { cx: "10", cy: "7", r: "4", key: "e45bow" }],
    ["path", { d: "M10.3 15H7a4 4 0 0 0-4 4v2", key: "3bnktk" }],
    ["circle", { cx: "17", cy: "17", r: "3", key: "18b49y" }],
    ["path", { d: "m21 21-1.9-1.9", key: "1g2n9r" }]
  ];
  const UserSearch = createLucideIcon("user-search", __iconNode$1);
  /**
   * @license lucide-react v1.16.0 - ISC
   *
   * This source code is licensed under the ISC license.
   * See the LICENSE file in the root directory of this source tree.
   */
  const __iconNode = [
    ["path", { d: "M12.8 19.6A2 2 0 1 0 14 16H2", key: "148xed" }],
    ["path", { d: "M17.5 8a2.5 2.5 0 1 1 2 4H2", key: "1u4tom" }],
    ["path", { d: "M9.8 4.4A2 2 0 1 1 11 8H2", key: "75valh" }]
  ];
  const Wind = createLucideIcon("wind", __iconNode);
  const SIMPLE_SERVICES = {
    references: {
      id: "references",
      label: "References",
      recommendedTorn: 15e5,
      recommendedHint: "$1.5M+ recommended",
      Icon: UserSearch
    },
    "friend-or-foe": {
      id: "friend-or-foe",
      label: "Friend or Foe",
      recommendedTorn: 24e6,
      recommendedHint: "$24M+ recommended",
      Icon: UserCheck,
      autofillSelf: true
    },
    meditation: {
      id: "meditation",
      label: "Meditation",
      recommendedTorn: 13e7,
      recommendedHint: "$130M+ recommended",
      Icon: Search,
      autofillSelf: true
    },
    "bounty-reveal": {
      id: "bounty-reveal",
      label: "Bounty Reveal",
      recommendedTorn: 55e5,
      recommendedHint: "$5.5M+ recommended",
      Icon: Locate
    },
    spies: {
      id: "spies",
      label: "Spies",
      recommendedTorn: 5e7,
      recommendedHint: "$50M+ recommended",
      Icon: HatGlasses,
      allowFactionTarget: true
    },
    loadout: {
      id: "loadout",
      label: "Loadout",
      recommendedTorn: 1e7,
      recommendedHint: "$10M+ recommended",
      Icon: Swords,
      allowFactionTarget: true
    }
  };
  const SIMPLE_SERVICE_IDS = Object.keys(
    SIMPLE_SERVICES
  );
  function isSimpleServiceId(value) {
    return value in SIMPLE_SERVICES;
  }
  function lossContractJsonToParty(row2) {
    return {
      id: row2.id,
      partyId: Number(row2.seller_xid),
      quantity: row2.quantity,
      endsAt: new Date(row2.ends_at).getTime()
    };
  }
  function redeemingFulfillmentJsonToParty(row2) {
    return {
      id: row2.id,
      partyId: Number(row2.fulfiller_xid),
      quantity: row2.xanax_total,
      endsAt: new Date(row2.ends_at).getTime()
    };
  }
  function bountyContractJsonToParty(row2) {
    return {
      id: row2.id,
      partyId: Number(row2.fulfiller_xid),
      quantity: row2.quantity,
      endsAt: new Date(row2.ends_at).getTime()
    };
  }
  function contributorJsonToContributor(row2) {
    return {
      sellerId: Number(row2.seller_xid),
      attacksVerified: Number(row2.attacks_verified)
    };
  }
  function buyerOrderProgressFromJson(payload) {
    var _a2;
    if (!((_a2 = payload == null ? void 0 : payload.order) == null ? void 0 : _a2.id)) return null;
    const row2 = payload.order;
    return {
      id: row2.id,
      contractType: row2.contract_type,
      buyerId: row2.buyer_xid,
      payPerLoss: Number(row2.pay_per_loss),
      quantity: row2.quantity,
      quantityRemaining: row2.quantity_remaining,
      escrowedTotal: Number(row2.escrowed_total),
      status: row2.status,
      isPaused: row2.is_paused ?? false,
      createdAt: new Date(row2.created_at).getTime(),
      completedQuantity: Number(payload.completed_quantity ?? 0),
      verifiedQuantity: Number(payload.verified_quantity ?? 0),
      contributors: (payload.contributors ?? []).map(contributorJsonToContributor),
      activeContracts: (payload.active_contracts ?? []).map(lossContractJsonToParty)
    };
  }
  function buyerOrdersProgressFromJson(payload) {
    if (!Array.isArray(payload)) return [];
    return payload.map(buyerOrderProgressFromJson).filter((order) => order != null);
  }
  function bountyOrderRowToActiveOrder(row2, activeContracts) {
    return {
      id: row2.id,
      buyerId: row2.buyer_xid,
      quantity: row2.quantity,
      quantityRemaining: row2.quantity_remaining,
      targetIds: [row2.target_id],
      bountyValueTorn: Number(row2.bounty_value_torn),
      escrowedTotal: Number(row2.escrowed_total),
      status: row2.status,
      createdAt: new Date(row2.created_at).getTime(),
      activeContracts
    };
  }
  function bountyOrderProgressFromJson(payload) {
    var _a2;
    if (!((_a2 = payload == null ? void 0 : payload.order) == null ? void 0 : _a2.id)) return null;
    return bountyOrderRowToActiveOrder(
      payload.order,
      (payload.active_contracts ?? []).map(bountyContractJsonToParty)
    );
  }
  function bountyOrdersProgressFromJson(payload) {
    if (!Array.isArray(payload)) return [];
    return payload.map(bountyOrderProgressFromJson).filter((order) => order != null);
  }
  function myRedeemingFromJson(payload) {
    var _a2;
    if (!((_a2 = payload == null ? void 0 : payload.request) == null ? void 0 : _a2.id)) return null;
    const row2 = payload.request;
    return {
      id: row2.id,
      requesterId: row2.requester_xid,
      quantity: row2.xanax_quantity,
      xanaxRemaining: row2.xanax_remaining,
      debitTotal: Number(row2.debit_total),
      status: row2.status,
      createdAt: new Date(row2.created_at).getTime(),
      completedQuantity: Number(payload.completed_quantity ?? 0),
      activeFulfillments: (payload.active_fulfillments ?? []).map(
        redeemingFulfillmentJsonToParty
      )
    };
  }
  function isOpenBuyerOrder(order) {
    if (!order) return false;
    if (order.status === "cancelled") return false;
    return order.quantity > 0 && order.quantityRemaining >= 0;
  }
  function isCompletedBuyerOrder(order) {
    return order.status === "filled" && order.activeContracts.length === 0;
  }
  function isVisibleBuyerOrder(order, dismissedIds) {
    if (order.status === "cancelled") return false;
    if (isCompletedBuyerOrder(order)) return !dismissedIds.has(order.id);
    return isOpenBuyerOrder(order);
  }
  function buyerOrderVerifiedCount(order) {
    return order.verifiedQuantity;
  }
  function buyerOrderProgressPercent(order) {
    if (order.quantity <= 0) return 0;
    return Math.min(
      100,
      Math.round(buyerOrderVerifiedCount(order) / order.quantity * 100)
    );
  }
  function buyerOrderUncompletedQuantity(order) {
    const inProgress = order.activeContracts.reduce(
      (sum, contract) => sum + contract.quantity,
      0
    );
    return order.quantityRemaining + inProgress;
  }
  function redeemingRequestUncompletedQuantity(request) {
    return Math.max(0, request.quantity - request.completedQuantity);
  }
  function bountyOrderUncompletedQuantity(order) {
    const inProgress = order.activeContracts.reduce(
      (sum, contract) => sum + contract.quantity,
      0
    );
    return order.quantityRemaining + inProgress;
  }
  function isVisibleBountyMarketOrder(order) {
    var _a2;
    if (order.status === "cancelled") return false;
    if (order.status === "open") return true;
    if (order.status === "filled") {
      if ((((_a2 = order.activeContracts) == null ? void 0 : _a2.length) ?? 0) > 0) return true;
      return order.quantityRemaining === 0;
    }
    return false;
  }
  function buyerOrderRowToListing(row2) {
    return {
      id: row2.id,
      sellerId: row2.buyer_xid,
      quantity: row2.quantity_remaining,
      payPerLoss: Number(row2.pay_per_loss),
      contractType: row2.contract_type
    };
  }
  function redeemingRowToListing(row2) {
    return {
      id: row2.id,
      requesterId: row2.requester_xid,
      quantity: row2.xanax_remaining,
      createdAt: new Date(row2.created_at).getTime()
    };
  }
  function lossContractToActive(contract) {
    return {
      listing: {
        id: contract.buyer_order_id,
        sellerId: contract.buyer_xid,
        quantity: contract.losses_remaining,
        payPerLoss: Number(contract.pay_per_loss),
        contractType: contract.contract_type
      },
      contractType: contract.contract_type,
      quantity: contract.quantity,
      lossesRemaining: contract.losses_remaining ?? 0,
      lossesVerified: contract.losses_verified ?? 0
    };
  }
  function lossContractEndsAt(contract) {
    return new Date(contract.ends_at).getTime();
  }
  function fulfillmentToActive(fulfillment, listing) {
    return {
      listing,
      xanaxTotal: fulfillment.xanax_total,
      xanaxRemaining: fulfillment.xanax_remaining ?? 0,
      xanaxVerified: fulfillment.xanax_verified ?? 0
    };
  }
  function fulfillmentEndsAt(fulfillment) {
    return new Date(fulfillment.ends_at).getTime();
  }
  const WITHDRAW_PERCENT_FEE_RATE = 0.05;
  function getWithdrawFee(withdrawAmount) {
    return Math.floor(withdrawAmount * WITHDRAW_PERCENT_FEE_RATE);
  }
  function getWithdrawAmount(xanaxCount) {
    return xanaxCount * WITHDRAW_MILLION;
  }
  function getWithdrawTotalDebit(xanaxCount) {
    const withdrawAmount = getWithdrawAmount(xanaxCount);
    return withdrawAmount + getWithdrawFee(withdrawAmount);
  }
  const BUYING_LISTINGS = [
    { id: "1", sellerId: 2847193, quantity: 185, payPerLoss: 6e5, contractType: "losses" },
    { id: "2", sellerId: 6102884, quantity: 42, payPerLoss: 584500, contractType: "losses" },
    { id: "3", sellerId: 1459771, quantity: 12, payPerLoss: 571e3, contractType: "losses" },
    { id: "4", sellerId: 9338502, quantity: 200, payPerLoss: 558e3, contractType: "losses" },
    { id: "5", sellerId: 4221065, quantity: 67, payPerLoss: 545250, contractType: "losses" },
    { id: "6", sellerId: 7890114, quantity: 8, payPerLoss: 532e3, contractType: "losses" },
    { id: "7", sellerId: 3556908, quantity: 156, payPerLoss: 519750, contractType: "losses" },
    { id: "8", sellerId: 8104337, quantity: 23, payPerLoss: 506e3, contractType: "losses" },
    { id: "9", sellerId: 5672441, quantity: 94, payPerLoss: 493500, contractType: "losses" },
    { id: "10", sellerId: 1993820, quantity: 31, payPerLoss: 48e4, contractType: "losses" },
    { id: "11", sellerId: 9771256, quantity: 178, payPerLoss: 467250, contractType: "losses" },
    { id: "12", sellerId: 2305619, quantity: 5, payPerLoss: 454e3, contractType: "losses" },
    { id: "13", sellerId: 6448073, quantity: 112, payPerLoss: 441500, contractType: "losses" },
    { id: "14", sellerId: 4889512, quantity: 49, payPerLoss: 428e3, contractType: "losses" },
    { id: "15", sellerId: 1127694, quantity: 163, payPerLoss: 415750, contractType: "losses" },
    { id: "16", sellerId: 7264381, quantity: 76, payPerLoss: 402e3, contractType: "losses" },
    { id: "17", sellerId: 3915208, quantity: 19, payPerLoss: 389500, contractType: "losses" },
    { id: "18", sellerId: 8553947, quantity: 138, payPerLoss: 376e3, contractType: "losses" },
    { id: "19", sellerId: 5041662, quantity: 55, payPerLoss: 362250, contractType: "losses" },
    { id: "20", sellerId: 2678409, quantity: 91, payPerLoss: 3e5, contractType: "losses" }
  ];
  function formatExtensionPoints(amount) {
    const n = Math.trunc(amount);
    const formatted = Math.abs(n).toLocaleString("en-US");
    return n < 0 ? `-${formatted} PTS` : `${formatted} PTS`;
  }
  function formatTornUserId(xid) {
    return String(Math.trunc(Number(xid)));
  }
  function formatSellerId(sellerId) {
    return formatTornUserId(sellerId);
  }
  function getSellerProfileUrl(sellerId) {
    return `https://www.torn.com/profiles.php?XID=${sellerId}`;
  }
  function sortListings(listings, field2, descending) {
    return [...listings].sort((a, b) => {
      const diff = a[field2] - b[field2];
      return descending ? -diff : diff;
    });
  }
  function findTopSelectableLossListing(listings, ownListingIds, currentUserXid) {
    const sorted = sortListings(
      listings.filter((listing) => listing.contractType === "losses"),
      "payPerLoss",
      true
    );
    return sorted.find(
      (listing) => listing.quantity > 0 && !ownListingIds.has(listing.id) && listing.sellerId !== currentUserXid
    ) ?? null;
  }
  const CONTRACT_TYPES = [
    "losses",
    "escapes",
    "stalemates"
  ];
  const CONTRACT_TYPE_LABELS = {
    losses: "Losses",
    escapes: "Escapes",
    stalemates: "Stalemates"
  };
  const CONTRACT_TYPE_SINGULAR = {
    losses: "Loss",
    escapes: "Escape",
    stalemates: "Stalemate"
  };
  function getPricePerLabel(type) {
    return `Price / ${CONTRACT_TYPE_SINGULAR[type]}`;
  }
  function getPayPerLabel(type) {
    return `Pay / ${CONTRACT_TYPE_SINGULAR[type]}`;
  }
  function getContractTypeBadge(type, status2 = "open") {
    return `${CONTRACT_TYPE_LABELS[type]} contract — ${status2}`;
  }
  function isContractType(value) {
    return CONTRACT_TYPES.includes(value);
  }
  function getContractType(order) {
    return order.contractType ?? "losses";
  }
  const SUFFIX_MULTIPLIER = {
    k: 1e3,
    m: 1e6,
    b: 1e9
  };
  function evaluateNumericInput(raw) {
    let s = raw.toLowerCase().replace(/,/g, "").trim();
    if (!s) return null;
    let suffix = "";
    if (/[kmb]$/.test(s)) {
      suffix = s.slice(-1);
      s = s.slice(0, -1);
    }
    s = s.replace(/[kmb]/g, "");
    if (!s || !/^\d*\.?\d+$/.test(s)) return null;
    const base = Number(s);
    if (!Number.isFinite(base) || base <= 0) return null;
    const mult = suffix ? SUFFIX_MULTIPLIER[suffix] ?? 1 : 1;
    return base * mult;
  }
  function formatIntegerDisplay(value, max) {
    if (!Number.isFinite(value) || value <= 0) return "";
    const clamped = Math.min(value, max);
    if (!Number.isInteger(clamped)) {
      return Math.floor(clamped).toLocaleString("en-US");
    }
    return clamped.toLocaleString("en-US");
  }
  function formatDecimalTyping(numericPart) {
    if (!numericPart) return "";
    if (numericPart === ".") return ".";
    const endsWithDot = numericPart.endsWith(".");
    const [intRaw, ...decParts] = numericPart.split(".");
    const decRaw = decParts.join("");
    const intDigits = intRaw.replace(/\D/g, "");
    const decDigits = decRaw.replace(/\D/g, "");
    let formattedInt = "";
    if (intDigits) {
      formattedInt = Number(intDigits).toLocaleString("en-US");
    } else if (endsWithDot || decDigits) {
      formattedInt = "0";
    }
    if (endsWithDot) return `${formattedInt}.`;
    if (decParts.length > 0) {
      return decDigits ? `${formattedInt}.${decDigits}` : formattedInt;
    }
    return formattedInt || intDigits;
  }
  function sanitizeNumericInput(raw, max) {
    let s = raw.toLowerCase().replace(/[^0-9.,kmb]/g, "");
    let suffix = "";
    if (/[kmb]$/.test(s)) {
      suffix = s.slice(-1);
      s = s.slice(0, -1);
    }
    s = s.replace(/[kmb]/g, "");
    const dotIndex = s.indexOf(".");
    if (dotIndex !== -1) {
      const before = s.slice(0, dotIndex + 1);
      const after = s.slice(dotIndex + 1).replace(/\./g, "");
      s = before + after;
    }
    const numericPart = s.replace(/,/g, "");
    if (!numericPart && !suffix) return "";
    if (suffix) {
      if (!numericPart) return "";
      const value = evaluateNumericInput(numericPart + suffix);
      if (value === null || value <= 0) return formatDecimalTyping(numericPart);
      return formatIntegerDisplay(value, max);
    }
    if (!numericPart.endsWith(".")) {
      const value = Number(numericPart);
      if (Number.isFinite(value) && value > max) {
        return formatIntegerDisplay(max, max);
      }
    }
    return formatDecimalTyping(numericPart);
  }
  function sanitizePriceInput(raw) {
    return sanitizeNumericInput(raw, BUYER_ORDER_PRICE_MAX);
  }
  function sanitizeQuantityInput(raw) {
    return sanitizeNumericInput(raw, BUYER_ORDER_QTY_MAX);
  }
  function parseWholeNumberInput(raw, min, max) {
    const value = evaluateNumericInput(raw);
    if (value === null || !Number.isFinite(value) || !Number.isInteger(value)) {
      return null;
    }
    if (value < min || value > max) return null;
    return value;
  }
  function parsePriceInput(raw) {
    return parseWholeNumberInput(raw, BUYER_ORDER_PRICE_MIN, BUYER_ORDER_PRICE_MAX);
  }
  function parseQuantityInput(raw) {
    return parseWholeNumberInput(raw, 1, BUYER_ORDER_QTY_MAX);
  }
  function sanitizeInsurancePremiumInput(raw) {
    const sanitized = sanitizeNumericInput(raw, INSURANCE_COVERAGE_MAX);
    const value = evaluateNumericInput(sanitized);
    if (value !== null && Number.isFinite(value) && Number.isInteger(value) && value > INSURANCE_COVERAGE_MAX) {
      return INSURANCE_COVERAGE_MAX.toLocaleString("en-US");
    }
    return sanitized;
  }
  function parseInsurancePremiumInput(raw) {
    return parseWholeNumberInput(
      raw,
      INSURANCE_COVERAGE_MIN,
      INSURANCE_COVERAGE_MAX
    );
  }
  function sanitizeBountyQuantityInput(raw) {
    return sanitizeNumericInput(raw, BOUNTY_QTY_MAX);
  }
  function parseBountyQuantityInput(raw) {
    return parseWholeNumberInput(raw, BOUNTY_QTY_MIN, BOUNTY_QTY_MAX);
  }
  const BOUNTY_VALUE_TORN_MAX = 1e10;
  function sanitizeBountyValueInput(raw) {
    return sanitizeNumericInput(raw, BOUNTY_VALUE_TORN_MAX);
  }
  function parseBountyValueInput(raw) {
    return parseWholeNumberInput(raw, 1, BOUNTY_VALUE_TORN_MAX);
  }
  const COMPANY_ID_MAX = 9999999999;
  function sanitizeCompanyIdInput(raw) {
    const digits = raw.replace(/\D/g, "");
    if (!digits) return "";
    const value = Number(digits);
    if (!Number.isFinite(value) || value <= 0) return digits;
    if (value > COMPANY_ID_MAX) return String(COMPANY_ID_MAX);
    return digits;
  }
  function parseCompanyIdInput(raw) {
    const digits = raw.replace(/\D/g, "");
    if (!digits) return null;
    const value = Number(digits);
    if (!Number.isFinite(value) || !Number.isInteger(value) || value <= 0) {
      return null;
    }
    if (value > COMPANY_ID_MAX) return null;
    return value;
  }
  function sanitizeAmountInput(raw, max) {
    return sanitizeNumericInput(raw, max);
  }
  const WORD_SHORTCUT_FRACTIONS = {
    max: 1,
    all: 1,
    full: 1,
    half: 1 / 2,
    quarter: 1 / 4,
    third: 1 / 3
  };
  function resolveAmountShortcut(raw, referenceMax) {
    if (!Number.isFinite(referenceMax) || referenceMax < 0) return null;
    const s = raw.toLowerCase().replace(/\s+/g, "").trim();
    if (!s) return null;
    let fraction = null;
    if (s in WORD_SHORTCUT_FRACTIONS) {
      fraction = WORD_SHORTCUT_FRACTIONS[s];
    } else if (/^\d+(?:\.\d+)?%$/.test(s)) {
      fraction = Number(s.slice(0, -1)) / 100;
    } else if (/^\d+\/\d+$/.test(s)) {
      const [numerator, denominator] = s.split("/").map(Number);
      if (denominator > 0) fraction = numerator / denominator;
    }
    if (fraction !== null) {
      return Math.max(0, Math.round(referenceMax * fraction));
    }
    const evaluated = evaluateNumericInput(s);
    if (evaluated === null) return null;
    return Math.max(0, Math.round(evaluated));
  }
  const WORD_SHORTCUTS = Object.keys(WORD_SHORTCUT_FRACTIONS);
  function isCompleteShortcut(raw) {
    const s = raw.toLowerCase().replace(/\s+/g, "").trim();
    if (!s) return false;
    return WORD_SHORTCUTS.includes(s) || /^\d+(?:\.\d+)?%$/.test(s) || /^\d+\/\d+$/.test(s) || /^\d[\d.,]*[kmb]$/.test(s);
  }
  function isShortcutInProgress(raw) {
    const s = raw.toLowerCase().replace(/\s+/g, "").trim();
    if (!s) return false;
    if (/^\d+\/$/.test(s)) return true;
    return WORD_SHORTCUTS.some((word) => word !== s && word.startsWith(s));
  }
  function buyerOrderToListing(order) {
    return {
      id: order.id,
      sellerId: order.buyerId,
      quantity: order.quantityRemaining,
      payPerLoss: order.payPerLoss,
      contractType: getContractType(order)
    };
  }
  function createBuyerOrder$1(buyerId, payPerLoss, quantity2, contractType = "losses") {
    const id2 = `buyer-${buyerId}-${contractType}-${Date.now()}`;
    return {
      id: id2,
      contractType,
      buyerId,
      payPerLoss,
      quantity: quantity2,
      quantityRemaining: quantity2,
      escrowedTotal: payPerLoss * quantity2,
      status: "open",
      isPaused: false,
      createdAt: Date.now(),
      completedQuantity: 0,
      verifiedQuantity: 0,
      contributors: [],
      activeContracts: []
    };
  }
  function getBuyerOrderRefund(order) {
    return order.payPerLoss * order.quantityRemaining;
  }
  function getOpenBuyerOrderForType(orders, contractType) {
    return orders.find(
      (order) => isOpenBuyerOrder(order) && getContractType(order) === contractType
    ) ?? null;
  }
  function upsertBuyerOrderByType(orders, order) {
    const type = getContractType(order);
    return [...orders.filter((o) => getContractType(o) !== type), order];
  }
  function getRedeemingPayAmount(quantity2) {
    const xanaxCost = quantity2 * WITHDRAW_MILLION;
    const platformFee = Math.floor(
      xanaxCost * (REDEEMING_PAY_PERCENT / 100)
    );
    return xanaxCost + platformFee;
  }
  const REDEEMING_LISTINGS = [
    { id: "redeem-dummy-1", requesterId: 2847193, quantity: 1, createdAt: 0 },
    { id: "redeem-dummy-2", requesterId: 5391028, quantity: 3, createdAt: 0 },
    { id: "redeem-dummy-3", requesterId: 7104662, quantity: 5, createdAt: 0 },
    { id: "redeem-dummy-4", requesterId: 3882415, quantity: 8, createdAt: 0 },
    { id: "redeem-dummy-5", requesterId: 9256701, quantity: 10, createdAt: 0 }
  ];
  function createRedeemingListing(quantity2) {
    return {
      id: `redeem-${Date.now()}`,
      requesterId: REDEEMING_REQUESTER_PLACEHOLDER_ID,
      quantity: quantity2,
      createdAt: Date.now()
    };
  }
  function formatRequesterId(requesterId) {
    return formatSellerId(requesterId);
  }
  function getRequesterProfileUrl(requesterId) {
    return getSellerProfileUrl(requesterId);
  }
  function formatRedeemingPay(quantity2) {
    return formatExtensionPoints(getRedeemingPayAmount(quantity2));
  }
  function sortRedeemingListings(listings, field2, descending) {
    return [...listings].sort((a, b) => {
      const aVal = field2 === "pay" ? getRedeemingPayAmount(a.quantity) : a[field2];
      const bVal = field2 === "pay" ? getRedeemingPayAmount(b.quantity) : b[field2];
      const diff = aVal - bVal;
      return descending ? -diff : diff;
    });
  }
  function computeBountyPlacementCostTorn(bountyValueTorn) {
    return Math.round(bountyValueTorn * 1.5);
  }
  function computeBountyPerContractPts(bountyValueTorn, averageXanaxPrice, convertTornToPts) {
    const serviceFeePts = BOUNTY_SERVICE_FEE_PTS;
    if (averageXanaxPrice == null || !Number.isFinite(averageXanaxPrice)) {
      return { placementPts: null, serviceFeePts, totalPts: serviceFeePts };
    }
    const placementTorn = computeBountyPlacementCostTorn(bountyValueTorn);
    const placementPts = convertTornToPts(placementTorn, averageXanaxPrice);
    return {
      placementPts,
      serviceFeePts,
      totalPts: placementPts + serviceFeePts
    };
  }
  function computeBountyOrderTotalPts(quantity2, bountyValueTorn, averageXanaxPrice, convertTornToPts) {
    const per = computeBountyPerContractPts(
      bountyValueTorn,
      averageXanaxPrice,
      convertTornToPts
    );
    const serviceFeeTotalPts = quantity2 * per.serviceFeePts;
    const placementTotalPts = per.placementPts != null ? quantity2 * per.placementPts : null;
    let bountyCostPts = null;
    let tornFeePts = null;
    if (averageXanaxPrice != null && Number.isFinite(averageXanaxPrice)) {
      bountyCostPts = convertTornToPts(bountyValueTorn * quantity2, averageXanaxPrice);
      tornFeePts = convertTornToPts(
        Math.round(bountyValueTorn * 0.5) * quantity2,
        averageXanaxPrice
      );
    }
    const totalPts = bountyCostPts != null && tornFeePts != null ? bountyCostPts + tornFeePts + serviceFeeTotalPts : serviceFeeTotalPts;
    return {
      totalPts,
      perContractPts: per.totalPts,
      serviceFeeTotalPts,
      placementTotalPts,
      bountyCostPts,
      tornFeePts
    };
  }
  function computeBountyMultiTargetOrderTotalPts(quantity2, targetCount, bountyValueTorn, averageXanaxPrice, convertTornToPts) {
    const perContract = computeBountyOrderTotalPts(
      quantity2,
      bountyValueTorn,
      averageXanaxPrice,
      convertTornToPts
    );
    if (targetCount <= 1) return perContract;
    const scale2 = (value) => value != null ? value * targetCount : null;
    return {
      totalPts: scale2(perContract.totalPts),
      perContractPts: perContract.perContractPts,
      serviceFeeTotalPts: perContract.serviceFeeTotalPts * targetCount,
      placementTotalPts: scale2(perContract.placementTotalPts),
      bountyCostPts: scale2(perContract.bountyCostPts),
      tornFeePts: scale2(perContract.tornFeePts)
    };
  }
  function computeBountyListingCostTorn(quantityRemaining, bountyValueTorn) {
    return computeBountyPlacementCostTorn(bountyValueTorn) * quantityRemaining;
  }
  function sanitizeBountyTargetIdsInput(raw) {
    return raw.replace(/[^\d,\s]/g, "");
  }
  function parseBountyTargetIds(raw) {
    const trimmed = raw.trim();
    if (!trimmed) return null;
    const parts = trimmed.split(/[,\s]+/).filter(Boolean);
    if (parts.length === 0) return null;
    const ids = [];
    for (const part of parts) {
      if (!/^\d+$/.test(part)) return null;
      const id2 = Number(part);
      if (!Number.isFinite(id2) || id2 <= 0) return null;
      ids.push(id2);
    }
    return ids;
  }
  const EMPTY_PAYOUT_CONVERSION = {
    price: null,
    loading: false,
    error: null,
    permissionError: false
  };
  function convertScriptDollarsToTornDollars(scriptPayout, averageXanaxPrice) {
    return Math.round(
      scriptPayout / SCRIPT_DOLLARS_PER_XANAX * averageXanaxPrice
    );
  }
  function convertTornDollarsToScriptPoints(tornAmount, averageXanaxPrice) {
    return Math.round(
      tornAmount / averageXanaxPrice * SCRIPT_DOLLARS_PER_XANAX
    );
  }
  function formatMoney(amount) {
    return `$${Math.round(amount).toLocaleString("en-US")}`;
  }
  function formatPointsAsXanax(points) {
    return `${formatXanaxAmount(points)} Xanax`;
  }
  function formatXanaxAmount(points) {
    const xanax = points / SCRIPT_DOLLARS_PER_XANAX;
    const rounded = Number.isInteger(xanax) ? xanax : Math.round(xanax * 10) / 10;
    return rounded.toLocaleString("en-US", { maximumFractionDigits: 1 });
  }
  function formatPayoutFormula(scriptAmount, averageXanaxPrice) {
    return `${formatExtensionPoints(scriptAmount)} ÷ 0.${Math.round(averageXanaxPrice).toLocaleString("en-US")}`;
  }
  function useContractCountdown(endsAt, onExpired) {
    const [remainingSeconds, setRemainingSeconds] = reactExports.useState(0);
    reactExports.useEffect(() => {
      if (!endsAt) {
        setRemainingSeconds(0);
        return;
      }
      let expiredCalled = false;
      const tick = () => {
        const left = Math.max(0, Math.ceil((endsAt - Date.now()) / 1e3));
        setRemainingSeconds(left);
        if (left === 0 && !expiredCalled) {
          expiredCalled = true;
          onExpired == null ? void 0 : onExpired();
        }
      };
      tick();
      const id2 = globalThis.setInterval(tick, 1e3);
      return () => globalThis.clearInterval(id2);
    }, [endsAt, onExpired]);
    return remainingSeconds;
  }
  function useServiceOrder(config, deps) {
    const {
      tornXid,
      loadEnabled,
      useLiveMarket,
      balance,
      setOfflineBalance,
      requireAuthOrPrompt
    } = deps;
    const configRef = reactExports.useRef(config);
    configRef.current = config;
    const [modalOpen, setModalOpen] = reactExports.useState(false);
    const [pending, setPending] = reactExports.useState(null);
    const [active, setActive] = reactExports.useState([]);
    const [activeFulfillment, setActiveFulfillment] = reactExports.useState(
      null
    );
    const [fulfillmentEndsAt2, setFulfillmentEndsAt] = reactExports.useState(
      null
    );
    const [turnInState, setTurnInState] = reactExports.useState("idle");
    const [turnInError2, setTurnInError] = reactExports.useState(null);
    const [pendingCancel, setPendingCancel] = reactExports.useState(null);
    reactExports.useEffect(() => {
      if (!loadEnabled) return;
      setActive(configRef.current.readStoredSync(tornXid));
      void configRef.current.load(tornXid).then(setActive);
    }, [tornXid, loadEnabled]);
    const escrowTotal = reactExports.useMemo(
      () => active.reduce((sum, o) => sum + o.escrowedPts, 0),
      [active]
    );
    const availableBalance = useLiveMarket ? balance - escrowTotal : balance;
    const clearFulfillment = reactExports.useCallback(() => {
      setActiveFulfillment(null);
      setFulfillmentEndsAt(null);
      setTurnInState("idle");
      setTurnInError(null);
    }, []);
    const secondsRemaining = useContractCountdown(
      fulfillmentEndsAt2,
      clearFulfillment
    );
    const timerActive = fulfillmentEndsAt2 != null && secondsRemaining > 0;
    const showContractPanel = timerActive && activeFulfillment != null;
    const open = reactExports.useCallback(() => {
      if (!requireAuthOrPrompt()) return;
      setModalOpen(true);
    }, [requireAuthOrPrompt]);
    const proceed = reactExports.useCallback((order) => {
      setPending(order);
    }, []);
    const confirmBack = reactExports.useCallback(() => {
      setPending(null);
    }, []);
    const confirm2 = reactExports.useCallback(() => {
      if (!pending) return;
      if (pending.totalCostPts > availableBalance) return;
      const createdAt = Date.now();
      const next = configRef.current.buildActive(pending, createdAt);
      setActive((prev) => {
        const arr = [...prev.filter((o) => o.status === "open"), next];
        void configRef.current.save(tornXid, arr);
        return arr;
      });
      if (!useLiveMarket) {
        setOfflineBalance((b) => b - pending.totalCostPts);
      }
      setPending(null);
      setModalOpen(false);
    }, [pending, availableBalance, tornXid, useLiveMarket, setOfflineBalance]);
    const take = reactExports.useCallback(
      (order) => {
        setActiveFulfillment(order);
        setFulfillmentEndsAt(Date.now() + configRef.current.countdownSeconds * 1e3);
        setTurnInState("idle");
        setTurnInError(null);
      },
      []
    );
    const turnIn = reactExports.useCallback(() => {
      var _a2, _b;
      if (activeFulfillment) (_b = (_a2 = configRef.current).onCompleted) == null ? void 0 : _b.call(_a2, activeFulfillment);
      clearFulfillment();
    }, [activeFulfillment, clearFulfillment]);
    const requestCancel = reactExports.useCallback((order) => {
      setPendingCancel(order);
    }, []);
    const cancelDismiss = reactExports.useCallback(() => {
      setPendingCancel(null);
    }, []);
    const cancelConfirm = reactExports.useCallback(() => {
      const order = pendingCancel;
      if (!order) return;
      setActive((prev) => {
        const arr = prev.filter((o) => o.id !== order.id);
        void configRef.current.save(tornXid, arr);
        return arr;
      });
      if (!useLiveMarket) {
        setOfflineBalance((b) => b + order.escrowedPts);
      }
      setPendingCancel(null);
    }, [pendingCancel, tornXid, useLiveMarket, setOfflineBalance]);
    return {
      modalOpen,
      setModalOpen,
      pending,
      setPending,
      active,
      setActive,
      escrowTotal,
      availableBalance,
      activeFulfillment,
      fulfillmentEndsAt: fulfillmentEndsAt2,
      secondsRemaining,
      timerActive,
      showContractPanel,
      turnInState,
      setTurnInState,
      turnInError: turnInError2,
      setTurnInError,
      pendingCancel,
      open,
      proceed,
      confirmBack,
      confirm: confirm2,
      take,
      turnIn,
      requestCancel,
      cancelDismiss,
      cancelConfirm,
      clearFulfillment
    };
  }
  const PLINK_URL = "https://www.torn.com/audio/chat/Plink_2.mp3";
  const DEFAULT_ALERT_VOLUME_PERCENT = 100;
  function playLossMarketAlertSound(volumePercent = DEFAULT_ALERT_VOLUME_PERCENT) {
    const audio = new Audio(PLINK_URL);
    const clamped = Math.min(100, Math.max(0, volumePercent)) / 100;
    audio.volume = clamped;
    void audio.play().catch(() => {
    });
  }
  const THRESHOLD_KEY_PREFIX = "alert_threshold_";
  const ESCAPE_THRESHOLD_KEY_PREFIX = "alert_escape_threshold_";
  const STALEMATE_THRESHOLD_KEY_PREFIX = "alert_stalemate_threshold_";
  const WITHDRAWAL_THRESHOLD_KEY_PREFIX = "alert_withdrawal_threshold_";
  const BOUNTY_THRESHOLD_KEY_PREFIX = "alert_bounty_threshold_";
  const EMBARGO_THRESHOLD_KEY_PREFIX = "alert_embargo_threshold_";
  const PRODUCTIVITY_THRESHOLD_KEY_PREFIX = "alert_productivity_threshold_";
  const FLIGHT_DELAY_THRESHOLD_KEY_PREFIX = "alert_flight_delay_threshold_";
  const SIMPLE_SERVICE_THRESHOLD_KEY_PREFIX = "alert_simple_service_";
  const VOLUME_KEY_PREFIX = "alert_volume_";
  const MARKET_ALERT_KEY_PREFIX = {
    losses: THRESHOLD_KEY_PREFIX,
    escapes: ESCAPE_THRESHOLD_KEY_PREFIX,
    stalemates: STALEMATE_THRESHOLD_KEY_PREFIX
  };
  function thresholdKey(tornXid) {
    return `${THRESHOLD_KEY_PREFIX}${tornXid}`;
  }
  function marketAlertKey(type, tornXid) {
    return `${MARKET_ALERT_KEY_PREFIX[type]}${tornXid}`;
  }
  function withdrawalThresholdKey(tornXid) {
    return `${WITHDRAWAL_THRESHOLD_KEY_PREFIX}${tornXid}`;
  }
  function bountyThresholdKey(tornXid) {
    return `${BOUNTY_THRESHOLD_KEY_PREFIX}${tornXid}`;
  }
  function embargoThresholdKey(tornXid) {
    return `${EMBARGO_THRESHOLD_KEY_PREFIX}${tornXid}`;
  }
  function productivityThresholdKey(tornXid) {
    return `${PRODUCTIVITY_THRESHOLD_KEY_PREFIX}${tornXid}`;
  }
  function flightDelayThresholdKey(tornXid) {
    return `${FLIGHT_DELAY_THRESHOLD_KEY_PREFIX}${tornXid}`;
  }
  function volumeKey(tornXid) {
    return `${VOLUME_KEY_PREFIX}${tornXid}`;
  }
  function clampVolumePercent(value) {
    if (!Number.isFinite(value)) return DEFAULT_ALERT_VOLUME_PERCENT;
    return Math.min(100, Math.max(0, Math.round(value)));
  }
  async function loadAlertThreshold(tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        thresholdKey(tornXid)
      );
      if (typeof raw === "number" && Number.isFinite(raw)) return raw;
      return null;
    } catch {
      return null;
    }
  }
  async function saveAlertThreshold(tornXid, value) {
    const key = thresholdKey(tornXid);
    try {
      if (value === null) {
        await getPlatformRuntime().storage.remove(key);
      } else if (Number.isFinite(value)) {
        await getPlatformRuntime().storage.set(key, value);
      }
    } catch {
    }
  }
  async function loadAlertVolume(tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        volumeKey(tornXid)
      );
      if (typeof raw === "number" && Number.isFinite(raw)) {
        return clampVolumePercent(raw);
      }
      return DEFAULT_ALERT_VOLUME_PERCENT;
    } catch {
      return DEFAULT_ALERT_VOLUME_PERCENT;
    }
  }
  async function saveAlertVolume(tornXid, volumePercent) {
    try {
      await getPlatformRuntime().storage.set(volumeKey(tornXid), clampVolumePercent(volumePercent));
    } catch {
    }
  }
  async function loadAlertWithdrawalThreshold(tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        withdrawalThresholdKey(tornXid)
      );
      if (typeof raw === "number" && Number.isFinite(raw)) return raw;
      return null;
    } catch {
      return null;
    }
  }
  async function saveAlertWithdrawalThreshold(tornXid, value) {
    const key = withdrawalThresholdKey(tornXid);
    try {
      if (value === null) {
        await getPlatformRuntime().storage.remove(key);
      } else if (Number.isFinite(value)) {
        await getPlatformRuntime().storage.set(key, value);
      }
    } catch {
    }
  }
  async function loadAlertBountyThreshold(tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        bountyThresholdKey(tornXid)
      );
      if (typeof raw === "number" && Number.isFinite(raw)) return raw;
      return null;
    } catch {
      return null;
    }
  }
  async function saveAlertBountyThreshold(tornXid, value) {
    const key = bountyThresholdKey(tornXid);
    try {
      if (value === null) {
        await getPlatformRuntime().storage.remove(key);
      } else if (Number.isFinite(value)) {
        await getPlatformRuntime().storage.set(key, value);
      }
    } catch {
    }
  }
  async function loadAlertEmbargoThreshold(tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        embargoThresholdKey(tornXid)
      );
      if (typeof raw === "number" && Number.isFinite(raw)) return raw;
      return null;
    } catch {
      return null;
    }
  }
  async function saveAlertEmbargoThreshold(tornXid, value) {
    const key = embargoThresholdKey(tornXid);
    try {
      if (value === null) {
        await getPlatformRuntime().storage.remove(key);
      } else if (Number.isFinite(value)) {
        await getPlatformRuntime().storage.set(key, value);
      }
    } catch {
    }
  }
  async function loadAlertProductivityThreshold(tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        productivityThresholdKey(tornXid)
      );
      if (typeof raw === "number" && Number.isFinite(raw)) return raw;
      return null;
    } catch {
      return null;
    }
  }
  async function saveAlertProductivityThreshold(tornXid, value) {
    const key = productivityThresholdKey(tornXid);
    try {
      if (value === null) {
        await getPlatformRuntime().storage.remove(key);
      } else if (Number.isFinite(value)) {
        await getPlatformRuntime().storage.set(key, value);
      }
    } catch {
    }
  }
  async function loadAlertFlightDelayThreshold(tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        flightDelayThresholdKey(tornXid)
      );
      if (typeof raw === "number" && Number.isFinite(raw)) return raw;
      return null;
    } catch {
      return null;
    }
  }
  async function saveAlertFlightDelayThreshold(tornXid, value) {
    const key = flightDelayThresholdKey(tornXid);
    try {
      if (value === null) {
        await getPlatformRuntime().storage.remove(key);
      } else if (Number.isFinite(value)) {
        await getPlatformRuntime().storage.set(key, value);
      }
    } catch {
    }
  }
  function simpleServiceThresholdKey(kind, tornXid) {
    return `${SIMPLE_SERVICE_THRESHOLD_KEY_PREFIX}${kind}_${tornXid}`;
  }
  async function loadAlertSimpleServiceThreshold(kind, tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        simpleServiceThresholdKey(kind, tornXid)
      );
      if (typeof raw === "number" && Number.isFinite(raw)) return raw;
      return null;
    } catch {
      return null;
    }
  }
  async function saveAlertSimpleServiceThreshold(kind, tornXid, value) {
    const key = simpleServiceThresholdKey(kind, tornXid);
    try {
      if (value === null) {
        await getPlatformRuntime().storage.remove(key);
      } else if (Number.isFinite(value)) {
        await getPlatformRuntime().storage.set(key, value);
      }
    } catch {
    }
  }
  async function loadMarketAlertThreshold(type, tornXid) {
    if (type === "losses") {
      return loadAlertThreshold(tornXid);
    }
    try {
      const raw = await getPlatformRuntime().storage.get(
        marketAlertKey(type, tornXid)
      );
      if (typeof raw === "number" && Number.isFinite(raw)) return raw;
      return null;
    } catch {
      return null;
    }
  }
  async function saveMarketAlertThreshold(type, tornXid, value) {
    if (type === "losses") {
      return saveAlertThreshold(tornXid, value);
    }
    const key = marketAlertKey(type, tornXid);
    try {
      if (value === null) {
        await getPlatformRuntime().storage.remove(key);
      } else if (Number.isFinite(value)) {
        await getPlatformRuntime().storage.set(key, value);
      }
    } catch {
    }
  }
  const emptySimpleServiceThresholds = () => Object.fromEntries(
    SIMPLE_SERVICE_IDS.map((kind) => [kind, null])
  );
  function useAlertThresholds(tornXid) {
    const [alertThreshold, setAlertThreshold] = reactExports.useState(null);
    const [alertEscapeThreshold, setAlertEscapeThreshold] = reactExports.useState(null);
    const [alertStalemateThreshold, setAlertStalemateThreshold] = reactExports.useState(null);
    const [alertWithdrawalThreshold, setAlertWithdrawalThreshold] = reactExports.useState(null);
    const [alertBountyThreshold, setAlertBountyThreshold] = reactExports.useState(null);
    const [alertEmbargoThreshold, setAlertEmbargoThreshold] = reactExports.useState(null);
    const [alertProductivityThreshold, setAlertProductivityThreshold] = reactExports.useState(null);
    const [alertFlightDelayThreshold, setAlertFlightDelayThreshold] = reactExports.useState(null);
    const [alertSimpleServiceThresholds, setAlertSimpleServiceThresholds] = reactExports.useState(emptySimpleServiceThresholds);
    const [alertVolume, setAlertVolume] = reactExports.useState(DEFAULT_ALERT_VOLUME_PERCENT);
    reactExports.useEffect(() => {
      if (tornXid == null) {
        setAlertThreshold(null);
        setAlertEscapeThreshold(null);
        setAlertStalemateThreshold(null);
        setAlertWithdrawalThreshold(null);
        setAlertBountyThreshold(null);
        setAlertEmbargoThreshold(null);
        setAlertProductivityThreshold(null);
        setAlertFlightDelayThreshold(null);
        setAlertSimpleServiceThresholds(emptySimpleServiceThresholds());
        setAlertVolume(DEFAULT_ALERT_VOLUME_PERCENT);
        return;
      }
      let cancelled = false;
      void Promise.all([
        loadMarketAlertThreshold("losses", tornXid),
        loadMarketAlertThreshold("escapes", tornXid),
        loadMarketAlertThreshold("stalemates", tornXid),
        loadAlertWithdrawalThreshold(tornXid),
        loadAlertBountyThreshold(tornXid),
        loadAlertEmbargoThreshold(tornXid),
        loadAlertProductivityThreshold(tornXid),
        loadAlertFlightDelayThreshold(tornXid),
        loadAlertVolume(tornXid)
      ]).then(
        ([
          storedLossThreshold,
          storedEscapeThreshold,
          storedStalemateThreshold,
          storedWithdrawalThreshold,
          storedBountyThreshold,
          storedEmbargoThreshold,
          storedProductivityThreshold,
          storedFlightDelayThreshold,
          storedVolume
        ]) => {
          if (cancelled) return;
          setAlertThreshold(storedLossThreshold);
          setAlertEscapeThreshold(storedEscapeThreshold);
          setAlertStalemateThreshold(storedStalemateThreshold);
          setAlertWithdrawalThreshold(storedWithdrawalThreshold);
          setAlertBountyThreshold(storedBountyThreshold);
          setAlertEmbargoThreshold(storedEmbargoThreshold);
          setAlertProductivityThreshold(storedProductivityThreshold);
          setAlertFlightDelayThreshold(storedFlightDelayThreshold);
          setAlertVolume(storedVolume);
        }
      );
      void Promise.all(
        SIMPLE_SERVICE_IDS.map(
          (kind) => loadAlertSimpleServiceThreshold(kind, tornXid).then(
            (value) => [kind, value]
          )
        )
      ).then((entries) => {
        if (cancelled) return;
        setAlertSimpleServiceThresholds((prev) => {
          const next = { ...prev };
          for (const [kind, value] of entries) next[kind] = value;
          return next;
        });
      });
      return () => {
        cancelled = true;
      };
    }, [tornXid]);
    const handlers = reactExports.useMemo(() => {
      const persist = (setter, save2) => (value) => {
        setter(value);
        if (tornXid != null) void save2(tornXid, value);
      };
      return {
        handleAlertThresholdChange: persist(
          setAlertThreshold,
          (xid, v) => saveMarketAlertThreshold("losses", xid, v)
        ),
        handleAlertEscapeThresholdChange: persist(
          setAlertEscapeThreshold,
          (xid, v) => saveMarketAlertThreshold("escapes", xid, v)
        ),
        handleAlertStalemateThresholdChange: persist(
          setAlertStalemateThreshold,
          (xid, v) => saveMarketAlertThreshold("stalemates", xid, v)
        ),
        handleAlertWithdrawalThresholdChange: persist(
          setAlertWithdrawalThreshold,
          saveAlertWithdrawalThreshold
        ),
        handleAlertBountyThresholdChange: persist(
          setAlertBountyThreshold,
          saveAlertBountyThreshold
        ),
        handleAlertEmbargoThresholdChange: persist(
          setAlertEmbargoThreshold,
          saveAlertEmbargoThreshold
        ),
        handleAlertProductivityThresholdChange: persist(
          setAlertProductivityThreshold,
          saveAlertProductivityThreshold
        ),
        handleAlertFlightDelayThresholdChange: persist(
          setAlertFlightDelayThreshold,
          saveAlertFlightDelayThreshold
        ),
        handleAlertSimpleServiceThresholdChange: (kind, value) => {
          setAlertSimpleServiceThresholds((prev) => ({ ...prev, [kind]: value }));
          if (tornXid != null) {
            void saveAlertSimpleServiceThreshold(kind, tornXid, value);
          }
        },
        handleAlertVolumeChange: (volumePercent) => {
          setAlertVolume(volumePercent);
          if (tornXid != null) void saveAlertVolume(tornXid, volumePercent);
        }
      };
    }, [tornXid]);
    const settingsProps = reactExports.useMemo(
      () => ({
        alertThreshold,
        onAlertThresholdChange: handlers.handleAlertThresholdChange,
        alertEscapeThreshold,
        onAlertEscapeThresholdChange: handlers.handleAlertEscapeThresholdChange,
        alertStalemateThreshold,
        onAlertStalemateThresholdChange: handlers.handleAlertStalemateThresholdChange,
        alertWithdrawalThreshold,
        onAlertWithdrawalThresholdChange: handlers.handleAlertWithdrawalThresholdChange,
        alertBountyThreshold,
        onAlertBountyThresholdChange: handlers.handleAlertBountyThresholdChange,
        alertEmbargoThreshold,
        onAlertEmbargoThresholdChange: handlers.handleAlertEmbargoThresholdChange,
        alertProductivityThreshold,
        onAlertProductivityThresholdChange: handlers.handleAlertProductivityThresholdChange,
        alertFlightDelayThreshold,
        onAlertFlightDelayThresholdChange: handlers.handleAlertFlightDelayThresholdChange,
        alertSimpleServiceThresholds,
        onAlertSimpleServiceThresholdChange: handlers.handleAlertSimpleServiceThresholdChange,
        alertVolume,
        onAlertVolumeChange: handlers.handleAlertVolumeChange
      }),
      [
        alertThreshold,
        alertEscapeThreshold,
        alertStalemateThreshold,
        alertWithdrawalThreshold,
        alertBountyThreshold,
        alertEmbargoThreshold,
        alertProductivityThreshold,
        alertFlightDelayThreshold,
        alertSimpleServiceThresholds,
        alertVolume,
        handlers
      ]
    );
    return {
      alertThreshold,
      alertEscapeThreshold,
      alertStalemateThreshold,
      alertWithdrawalThreshold,
      alertBountyThreshold,
      alertEmbargoThreshold,
      alertProductivityThreshold,
      alertFlightDelayThreshold,
      alertSimpleServiceThresholds,
      alertVolume,
      ...handlers,
      settingsProps
    };
  }
  let client = null;
  let activeToken = null;
  async function bindRealtimeAuth(supabase2, accessToken) {
    await Promise.resolve(supabase2.realtime.setAuth(accessToken));
  }
  function getSupabase(session) {
    if (!isSupabaseConfigured()) {
      throw new Error("Supabase is not configured");
    }
    if (client && activeToken === session.access_token) {
      return client;
    }
    if (client) {
      void client.removeAllChannels();
    }
    const accessToken = session.access_token;
    const platformFetch = getPlatformRuntime().fetch;
    client = supabaseJs.createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
      global: {
        fetch: platformFetch,
        headers: {
          Authorization: `Bearer ${accessToken}`
        }
      },
      accessToken: async () => accessToken,
      auth: {
        persistSession: false,
        autoRefreshToken: false,
        detectSessionInUrl: false
      }
    });
    activeToken = accessToken;
    return client;
  }
  function resetSupabaseClient() {
    if (client) {
      void client.removeAllChannels();
    }
    client = null;
    activeToken = null;
  }
  let anonClient = null;
  function getAnonSupabase() {
    if (!isSupabaseConfigured()) {
      throw new Error("Supabase is not configured");
    }
    if (!anonClient) {
      const platformFetch = getPlatformRuntime().fetch;
      anonClient = supabaseJs.createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
        global: {
          fetch: platformFetch
        },
        auth: {
          persistSession: false,
          autoRefreshToken: false,
          detectSessionInUrl: false
        }
      });
    }
    return anonClient;
  }
  async function fetchProfile(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("get_my_profile").maybeSingle();
    if (error2) throw new Error(error2.message);
    return data ?? null;
  }
  async function fetchEngagementSnapshot(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("get_my_engagement_snapshot");
    if (error2) throw new Error(error2.message);
    const row2 = data ?? {};
    return {
      profile: row2.profile ?? null,
      buyerProgress: row2.buyer_progress ?? [],
      redeemingProgress: row2.redeeming_progress ?? null,
      activeLossContract: row2.active_loss_contract ?? null,
      activeRedeemingFulfillment: row2.active_redeeming_fulfillment ?? null
    };
  }
  async function fetchOpenBuyerOrders(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("list_open_buyer_orders");
    if (error2) throw new Error(error2.message);
    return data ?? [];
  }
  async function fetchMyBuyerContractProgress(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("get_my_buyer_contract_progress");
    if (error2) throw new Error(error2.message);
    return data ?? [];
  }
  async function fetchMyRedeemingRequestProgress(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("get_my_redeeming_request_progress").maybeSingle();
    if (error2) throw new Error(error2.message);
    return data ?? null;
  }
  async function fetchOpenRedeemingRequests(supabase2) {
    const { data, error: error2 } = await supabase2.from("redeeming_requests").select("id,requester_xid,xanax_remaining,created_at").eq("status", "open").order("created_at", { ascending: false });
    if (error2) throw new Error(error2.message);
    return data ?? [];
  }
  async function fetchCachedBoards() {
    const res = await fetch(`${SITE_BASE_URL}/api/board`, { credentials: "omit" });
    if (!res.ok) throw new Error(`board fetch failed: ${res.status}`);
    const json = await res.json();
    return { buyer: json.buyer ?? [], redeeming: json.redeeming ?? [] };
  }
  async function fetchMyActiveLossContract(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("get_my_active_loss_contract").maybeSingle();
    if (error2) throw new Error(error2.message);
    return data ?? null;
  }
  async function fetchMyActiveRedeemingFulfillment(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("get_my_active_redeeming_fulfillment").maybeSingle();
    if (error2) throw new Error(error2.message);
    return data ?? null;
  }
  async function fetchOpenBountyOrders(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("list_open_bounty_orders");
    if (error2) throw new Error(error2.message);
    return data ?? [];
  }
  async function fetchMyBountyOrdersProgress(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("get_my_bounty_orders_progress");
    if (error2) throw new Error(error2.message);
    return data ?? [];
  }
  async function fetchMyActiveBountyContract(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("get_my_active_bounty_contract").maybeSingle();
    if (error2) throw new Error(error2.message);
    return data ?? null;
  }
  async function createBuyerOrder(supabase2, payPerLoss, quantity2, contractType) {
    const { data, error: error2 } = await supabase2.rpc("create_buyer_order", {
      p_pay_per_loss: payPerLoss,
      p_quantity: quantity2,
      p_contract_type: contractType
    }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function cancelBuyerOrder(supabase2, orderId) {
    const { data, error: error2 } = await supabase2.rpc("cancel_buyer_order", {
      p_order_id: orderId
    }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function setBuyerOrderPaused(supabase2, orderId, paused) {
    const { data, error: error2 } = await supabase2.rpc("set_buyer_order_paused", {
      p_order_id: orderId,
      p_paused: paused
    }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function acceptLossContract(supabase2, orderId, quantity2) {
    const { data, error: error2 } = await supabase2.rpc("accept_loss_contract", {
      p_order_id: orderId,
      p_quantity: quantity2
    }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function createRedeemingRequest(supabase2, xanaxQuantity) {
    const { data, error: error2 } = await supabase2.rpc("create_redeeming_request", {
      p_xanax_quantity: xanaxQuantity
    }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function cancelRedeemingRequest(supabase2, requestId) {
    const { data, error: error2 } = await supabase2.rpc("cancel_redeeming_request", {
      p_request_id: requestId
    }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function acceptRedeemingFulfillment(supabase2, requestId, xanaxQuantity) {
    const { data, error: error2 } = await supabase2.rpc("accept_redeeming_fulfillment", {
      p_request_id: requestId,
      p_xanax_quantity: xanaxQuantity
    }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function createBountyOrder(supabase2, targetId, quantity2, bountyValueTorn, escrowTotal) {
    const { data, error: error2 } = await supabase2.rpc("create_bounty_order", {
      p_target_id: targetId,
      p_quantity: quantity2,
      p_bounty_value_torn: bountyValueTorn,
      p_escrow_total: escrowTotal
    }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function cancelBountyOrder(supabase2, orderId) {
    const { data, error: error2 } = await supabase2.rpc("cancel_bounty_order", {
      p_order_id: orderId
    }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function acceptBountyContract(supabase2, orderId, quantity2) {
    const { data, error: error2 } = await supabase2.rpc("accept_bounty_contract", {
      p_order_id: orderId,
      p_quantity: quantity2
    }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function fetchOpenEmbargoOrders(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("list_open_embargo_orders");
    if (error2) throw new Error(error2.message);
    return data ?? [];
  }
  async function fetchMyEmbargoOrdersProgress(supabase2) {
    const { data, error: error2 } = await supabase2.rpc(
      "get_my_embargo_orders_progress"
    );
    if (error2) throw new Error(error2.message);
    return data ?? [];
  }
  async function fetchMyActiveEmbargoContract(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("get_my_active_embargo_contract").maybeSingle();
    if (error2) throw new Error(error2.message);
    return data ?? null;
  }
  async function createEmbargoOrder(supabase2, targetId, priceTorn, escrowTotal) {
    const { data, error: error2 } = await supabase2.rpc("create_embargo_order", {
      p_target_id: targetId,
      p_price_torn: priceTorn,
      p_escrow_total: escrowTotal
    }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function cancelEmbargoOrder(supabase2, orderId) {
    const { data, error: error2 } = await supabase2.rpc("cancel_embargo_order", { p_order_id: orderId }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function acceptEmbargoContract(supabase2, orderId) {
    const { data, error: error2 } = await supabase2.rpc("accept_embargo_contract", { p_order_id: orderId }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function fetchOpenReferencesOrders(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("list_open_references_orders");
    if (error2) throw new Error(error2.message);
    return data ?? [];
  }
  async function fetchMyReferencesOrdersProgress(supabase2) {
    const { data, error: error2 } = await supabase2.rpc(
      "get_my_references_orders_progress"
    );
    if (error2) throw new Error(error2.message);
    return data ?? [];
  }
  async function fetchMyActiveReferencesContract(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("get_my_active_references_contract").maybeSingle();
    if (error2) throw new Error(error2.message);
    return data ?? null;
  }
  async function createReferencesOrder(supabase2, targetId, priceTorn, escrowTotal) {
    const { data, error: error2 } = await supabase2.rpc("create_references_order", {
      p_target_id: targetId,
      p_price_torn: priceTorn,
      p_escrow_total: escrowTotal
    }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function cancelReferencesOrder(supabase2, orderId) {
    const { data, error: error2 } = await supabase2.rpc("cancel_references_order", { p_order_id: orderId }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function acceptReferencesContract(supabase2, orderId) {
    const { data, error: error2 } = await supabase2.rpc("accept_references_contract", { p_order_id: orderId }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function pollReferencesContract(supabase2, contractId, apiKey, report) {
    const { data, error: error2 } = await supabase2.functions.invoke(
      "poll_references_contract",
      { body: { contract_id: contractId, api_key: apiKey, report } }
    );
    if (error2) throw new Error(error2.message);
    if (!data) throw new Error("poll_references_contract: empty response");
    return data;
  }
  async function fetchOpenBountyRevealOrders(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("list_open_bounty_reveal_orders");
    if (error2) throw new Error(error2.message);
    return data ?? [];
  }
  async function fetchMyBountyRevealOrdersProgress(supabase2) {
    const { data, error: error2 } = await supabase2.rpc(
      "get_my_bounty_reveal_orders_progress"
    );
    if (error2) throw new Error(error2.message);
    return data ?? [];
  }
  async function fetchMyActiveBountyRevealContract(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("get_my_active_bounty_reveal_contract").maybeSingle();
    if (error2) throw new Error(error2.message);
    return data ?? null;
  }
  async function createBountyRevealOrder(supabase2, targetId, priceTorn, escrowTotal) {
    const { data, error: error2 } = await supabase2.rpc("create_bounty_reveal_order", {
      p_target_id: targetId,
      p_price_torn: priceTorn,
      p_escrow_total: escrowTotal
    }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function cancelBountyRevealOrder(supabase2, orderId) {
    const { data, error: error2 } = await supabase2.rpc("cancel_bounty_reveal_order", { p_order_id: orderId }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function acceptBountyRevealContract(supabase2, orderId) {
    const { data, error: error2 } = await supabase2.rpc("accept_bounty_reveal_contract", { p_order_id: orderId }).single();
    if (error2) throw new Error(error2.message);
    return data;
  }
  async function pollBountyRevealContract(supabase2, contractId, apiKey, report) {
    const { data, error: error2 } = await supabase2.functions.invoke(
      "poll_bounty_reveal_contract",
      { body: { contract_id: contractId, api_key: apiKey, report } }
    );
    if (error2) throw new Error(error2.message);
    if (!data) throw new Error("poll_bounty_reveal_contract: empty response");
    return data;
  }
  async function deleteMyAccount(supabase2) {
    const { error: error2 } = await supabase2.rpc("delete_my_account");
    if (error2) throw new Error(error2.message);
  }
  async function fetchReferralSummary(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("get_my_referral_summary");
    if (error2) throw new Error(error2.message);
    return data ?? null;
  }
  async function fetchMyReferrals(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("list_my_referrals");
    if (error2) throw new Error(error2.message);
    return data ?? [];
  }
  async function applyReferralCode(supabase2, code) {
    const { data, error: error2 } = await supabase2.rpc("apply_referral_code", {
      p_code: code
    });
    if (error2) throw new Error(error2.message);
    return data ?? null;
  }
  async function releaseMyStaleEngagements(supabase2) {
    const { error: error2 } = await supabase2.rpc("release_my_stale_engagements");
    if (error2) throw new Error(error2.message);
  }
  async function listMyInsurancePolicies(supabase2) {
    const { data, error: error2 } = await supabase2.rpc("list_my_insurance_policies");
    if (error2) throw new Error(error2.message);
    return data ?? [];
  }
  async function refreshInsurancePolicyPerks(supabase2, policyId, apiKey) {
    const { data, error: error2 } = await supabase2.functions.invoke(
      "refresh_insurance_policy_perks",
      { body: { policy_id: policyId, api_key: apiKey } }
    );
    if (error2) throw new Error(error2.message);
    if (!data) throw new Error("refresh_insurance_policy_perks: empty response");
    return data;
  }
  async function pollEmbargoContract(supabase2, contractId, apiKey) {
    const { data, error: error2 } = await supabase2.functions.invoke(
      "poll_embargo_contract",
      { body: { contract_id: contractId, api_key: apiKey } }
    );
    if (error2) throw new Error(error2.message);
    if (!data) throw new Error("poll_embargo_contract: empty response");
    return data;
  }
  function useReferrals(deps) {
    const { session, useBackend, refreshBalance, onError } = deps;
    const [referralsModalOpen, setReferralsModalOpen] = reactExports.useState(false);
    const [referralSummary, setReferralSummary] = reactExports.useState(
      null
    );
    const [referralList, setReferralList] = reactExports.useState([]);
    const [referralSummaryLoading, setReferralSummaryLoading] = reactExports.useState(false);
    const [referralsListLoading, setReferralsListLoading] = reactExports.useState(false);
    const [referralApplyError, setReferralApplyError] = reactExports.useState(
      null
    );
    const [referralApplying, setReferralApplying] = reactExports.useState(false);
    const [referralApplySuccess, setReferralApplySuccess] = reactExports.useState(false);
    const loadReferralSummary = reactExports.useCallback(
      async (activeSession) => {
        setReferralSummaryLoading(true);
        try {
          const summary = await fetchReferralSummary(
            getSupabase(activeSession)
          );
          setReferralSummary(summary);
        } catch (err) {
          setReferralSummary(null);
          onError(
            err instanceof Error ? err.message : "Failed to load referral info"
          );
        } finally {
          setReferralSummaryLoading(false);
        }
      },
      [onError]
    );
    const loadReferralList = reactExports.useCallback(
      async (activeSession) => {
        setReferralsListLoading(true);
        try {
          const rows = await fetchMyReferrals(getSupabase(activeSession));
          setReferralList(rows);
        } catch (err) {
          setReferralList([]);
          onError(
            err instanceof Error ? err.message : "Failed to load referral list"
          );
        } finally {
          setReferralsListLoading(false);
        }
      },
      [onError]
    );
    reactExports.useEffect(() => {
      if (!referralsModalOpen || !session || !useBackend) return;
      void loadReferralSummary(session);
      void loadReferralList(session);
    }, [
      referralsModalOpen,
      session,
      useBackend,
      loadReferralSummary,
      loadReferralList
    ]);
    const handleOpenReferrals = reactExports.useCallback(() => {
      setReferralApplyError(null);
      setReferralApplySuccess(false);
      setReferralsModalOpen(true);
    }, []);
    const handleCloseReferrals = reactExports.useCallback(() => {
      setReferralsModalOpen(false);
      setReferralApplyError(null);
      setReferralApplySuccess(false);
    }, []);
    const handleApplyReferralCode = reactExports.useCallback(
      async (code) => {
        if (!session || !useBackend) return;
        setReferralApplyError(null);
        setReferralApplySuccess(false);
        setReferralApplying(true);
        try {
          const summary = await applyReferralCode(
            getSupabase(session),
            code
          );
          setReferralSummary(summary);
          setReferralApplySuccess(true);
          await refreshBalance();
        } catch (err) {
          setReferralApplyError(
            err instanceof Error ? err.message : "Could not apply referral code"
          );
        } finally {
          setReferralApplying(false);
        }
      },
      [session, useBackend, refreshBalance]
    );
    return {
      referralsModalOpen,
      referralSummary,
      referralList,
      referralSummaryLoading,
      referralsListLoading,
      referralApplyError,
      referralApplying,
      referralApplySuccess,
      handleOpenReferrals,
      handleCloseReferrals,
      handleApplyReferralCode
    };
  }
  const STORAGE_KEY_PREFIX$5 = "presence_last_heartbeat_";
  const PRESENCE_PING_INTERVAL_MS = 60 * 6e4;
  function storageKey$5(tornXid) {
    return `${STORAGE_KEY_PREFIX$5}${tornXid}`;
  }
  function readLastHeartbeatAt(tornXid) {
    try {
      const raw = readLocalStorageWithMigration(localStorage, storageKey$5(tornXid));
      if (raw == null) return null;
      const ts = Number(raw);
      return Number.isFinite(ts) && ts > 0 ? ts : null;
    } catch {
      return null;
    }
  }
  function writeLastHeartbeatAt(tornXid, atMs) {
    try {
      writeLocalStorageCurrent(localStorage, storageKey$5(tornXid), String(atMs));
    } catch {
    }
  }
  function shouldPingPresence(tornXid, nowMs = Date.now()) {
    const last = readLastHeartbeatAt(tornXid);
    return last == null || nowMs - last >= PRESENCE_PING_INTERVAL_MS;
  }
  async function pingPresenceIfDue() {
    if (!isSupabaseConfigured()) return false;
    const session = await getPlatformRuntime().auth.getSession();
    if (!session) return false;
    if (!shouldPingPresence(session.torn_xid)) return true;
    const supabase2 = getSupabase(session);
    const { error: error2 } = await supabase2.rpc("upsert_extension_presence");
    if (error2) {
      console.warn(`${BRAND_LOG_PREFIX} presence ping failed`, error2.message);
      return false;
    }
    writeLastHeartbeatAt(session.torn_xid, Date.now());
    return true;
  }
  function initPresencePing() {
    if (!isSupabaseConfigured()) return;
    let cancelled = false;
    const run = () => {
      if (cancelled) return;
      void pingPresenceIfDue();
    };
    run();
    const intervalId = window.setInterval(run, PRESENCE_PING_INTERVAL_MS);
    window.addEventListener("beforeunload", () => {
      cancelled = true;
      window.clearInterval(intervalId);
    });
  }
  const CACHE_KEY_PREFIX$1 = "torn_api_permissions_";
  const EMPTY_CACHE = {
    itemReceiveLog: false,
    equipment: false,
    itemMarket: false
  };
  function cacheKey$2(tornXid) {
    return `${CACHE_KEY_PREFIX$1}${tornXid}`;
  }
  function isValidCache(value) {
    if (typeof value !== "object" || value === null) return false;
    const candidate = value;
    return typeof candidate.itemReceiveLog === "boolean" && typeof candidate.equipment === "boolean" && typeof candidate.itemMarket === "boolean";
  }
  function readTornApiPermissionsCacheSync(tornXid) {
    if (typeof localStorage === "undefined") return null;
    try {
      const raw = localStorage.getItem(cacheKey$2(tornXid));
      if (!raw) return null;
      const parsed = JSON.parse(raw);
      return isValidCache(parsed) ? parsed : null;
    } catch {
      return null;
    }
  }
  async function loadTornApiPermissionsCache(tornXid) {
    const sync = readTornApiPermissionsCacheSync(tornXid);
    if (sync) return sync;
    const stored = await getPlatformRuntime().storage.get(
      cacheKey$2(tornXid)
    );
    return isValidCache(stored) ? stored : null;
  }
  function isTornApiPermissionVerified(cache, permission) {
    return (cache == null ? void 0 : cache[permission]) === true;
  }
  async function setTornApiPermissionVerified(tornXid, permission) {
    const existing = await loadTornApiPermissionsCache(tornXid) ?? { ...EMPTY_CACHE };
    const next = {
      ...existing,
      [permission]: true
    };
    const key = cacheKey$2(tornXid);
    if (typeof localStorage !== "undefined") {
      localStorage.setItem(key, JSON.stringify(next));
    }
    await getPlatformRuntime().storage.set(key, next);
  }
  async function clearTornApiPermissionsCache(tornXid) {
    const key = cacheKey$2(tornXid);
    if (typeof localStorage !== "undefined") {
      localStorage.removeItem(key);
    }
    await getPlatformRuntime().storage.remove(key);
  }
  function useAuth() {
    const configured = isSupabaseConfigured();
    const platform = getPlatformRuntime();
    const [loading, setLoading] = reactExports.useState(configured);
    const [session, setSession] = reactExports.useState(null);
    const [error2, setError] = reactExports.useState(null);
    const refresh = reactExports.useCallback(async () => {
      if (!configured) {
        setLoading(false);
        setSession(null);
        return;
      }
      setLoading(true);
      setError(null);
      try {
        const nextSession = await platform.auth.getSession();
        if (nextSession) {
          const cached = await loadTornApiPermissionsCache(nextSession.torn_xid);
          if (!isTornApiPermissionVerified(cached, "itemReceiveLog")) {
            await setTornApiPermissionVerified(
              nextSession.torn_xid,
              "itemReceiveLog"
            );
          }
        }
        setSession(nextSession);
        if (nextSession) {
          void pingPresenceIfDue();
        }
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to load session");
        setSession(null);
      }
      setLoading(false);
    }, [configured, platform]);
    reactExports.useEffect(() => {
      void refresh();
    }, [refresh]);
    const signIn = reactExports.useCallback(async (apiKey) => {
      setError(null);
      try {
        const nextSession = await platform.auth.setApiKey(apiKey);
        await clearTornApiPermissionsCache(nextSession.torn_xid);
        await setTornApiPermissionVerified(nextSession.torn_xid, "itemReceiveLog");
        setSession(nextSession);
        resetSupabaseClient();
        void pingPresenceIfDue();
        return nextSession;
      } catch (err) {
        const message = err instanceof Error ? err.message : "Sign-in failed";
        setError(message);
        throw new Error(message);
      }
    }, [platform]);
    const signOut = reactExports.useCallback(async () => {
      const tornXid = (session == null ? void 0 : session.torn_xid) ?? null;
      await platform.auth.signOut();
      if (tornXid !== null) {
        await clearTornApiPermissionsCache(tornXid);
      }
      resetSupabaseClient();
      setSession(null);
    }, [platform, session]);
    return {
      configured,
      loading,
      session,
      error: error2,
      signIn,
      signOut,
      refresh
    };
  }
  const offlineState = {
    balance: DEFAULT_USER_BALANCE,
    marketListings: BUYING_LISTINGS,
    redeemingListings: REDEEMING_LISTINGS
  };
  const emptyBoardListings = [];
  const emptyRedeemingListings = [];
  const REALTIME_COALESCE_MS = 75;
  function balanceFromProfileRow(row2) {
    return row2 ? Number(row2.balance) : DEFAULT_USER_BALANCE;
  }
  function useMarketData(session, configured, { loadBoard }) {
    const useBackend = configured && session !== null;
    const guestMode = configured && session === null;
    const [engagementLoading, setEngagementLoading] = reactExports.useState(
      () => configured && session !== null
    );
    const [engagementReady, setEngagementReady] = reactExports.useState(
      () => !(configured && session !== null)
    );
    const [boardLoading2, setBoardLoading] = reactExports.useState(false);
    const [boardReady, setBoardReady] = reactExports.useState(false);
    const [error2, setError] = reactExports.useState(null);
    const [balance, setBalance] = reactExports.useState(offlineState.balance);
    const [marketListings, setMarketListings] = reactExports.useState(offlineState.marketListings);
    const [buyerOrders, setBuyerOrders] = reactExports.useState([]);
    const [redeemingListings, setRedeemingListings] = reactExports.useState(
      offlineState.redeemingListings
    );
    const [ownRedeemingListingIds, setOwnRedeemingListingIds] = reactExports.useState(
      /* @__PURE__ */ new Set()
    );
    const [myRedeemingRequest, setMyRedeemingRequest] = reactExports.useState(null);
    const [activeContract, setActiveContract] = reactExports.useState(null);
    const [contractEndsAt, setContractEndsAt] = reactExports.useState(null);
    const [activeLossContractId, setActiveLossContractId] = reactExports.useState(
      null
    );
    const [activeRedeemingFulfillment, setActiveRedeemingFulfillment] = reactExports.useState(null);
    const [redeemingContractEndsAt, setRedeemingContractEndsAt] = reactExports.useState(null);
    const [activeRedeemingFulfillmentId, setActiveRedeemingFulfillmentId] = reactExports.useState(null);
    const loading = engagementLoading || loadBoard && boardLoading2;
    const refreshSeqRef = reactExports.useRef(0);
    const engagementSeqRef = reactExports.useRef(0);
    const boardSeqRef = reactExports.useRef(0);
    const sessionRef = reactExports.useRef(session);
    sessionRef.current = session;
    const loadBoardRef = reactExports.useRef(loadBoard);
    loadBoardRef.current = loadBoard;
    const redeemingListingsRef = reactExports.useRef(redeemingListings);
    const myRedeemingRequestRef = reactExports.useRef(myRedeemingRequest);
    const activeRedeemingFulfillmentRowRef = reactExports.useRef(null);
    redeemingListingsRef.current = redeemingListings;
    myRedeemingRequestRef.current = myRedeemingRequest;
    const pendingRefreshRef = reactExports.useRef(/* @__PURE__ */ new Set());
    const flushTimerRef = reactExports.useRef(
      null
    );
    const scheduleRefresh = reactExports.useCallback((fn) => {
      pendingRefreshRef.current.add(fn);
      if (flushTimerRef.current != null) return;
      flushTimerRef.current = globalThis.setTimeout(() => {
        flushTimerRef.current = null;
        const fns = Array.from(pendingRefreshRef.current);
        pendingRefreshRef.current.clear();
        for (const run of fns) void run();
      }, REALTIME_COALESCE_MS);
    }, []);
    reactExports.useEffect(
      () => () => {
        if (flushTimerRef.current != null) {
          globalThis.clearTimeout(flushTimerRef.current);
          flushTimerRef.current = null;
        }
      },
      []
    );
    const clearBuyerOrder = reactExports.useCallback(() => {
      setBuyerOrders([]);
    }, []);
    const clearBoardListings = reactExports.useCallback(() => {
      buyerOverlayRef.current.clear();
      redeemOverlayRef.current.clear();
      redeemingListingsRef.current = emptyRedeemingListings;
      setMarketListings(emptyBoardListings);
      setRedeemingListings(emptyRedeemingListings);
      setBoardReady(false);
    }, []);
    const applyLossContract = reactExports.useCallback((row2) => {
      if (!(row2 == null ? void 0 : row2.id)) {
        setActiveContract(null);
        setContractEndsAt(null);
        setActiveLossContractId(null);
        return;
      }
      setActiveContract(lossContractToActive(row2));
      setContractEndsAt(lossContractEndsAt(row2));
      setActiveLossContractId(row2.id);
    }, []);
    const applyRedeemingFulfillment = reactExports.useCallback(
      (row2, requests) => {
        if (!(row2 == null ? void 0 : row2.id)) {
          activeRedeemingFulfillmentRowRef.current = null;
          setActiveRedeemingFulfillment(null);
          setRedeemingContractEndsAt(null);
          setActiveRedeemingFulfillmentId(null);
          return;
        }
        activeRedeemingFulfillmentRowRef.current = row2;
        const listing = requests.find((r) => r.id === row2.request_id) ?? {
          id: row2.request_id,
          requesterId: row2.requester_xid,
          quantity: row2.xanax_total,
          createdAt: Date.now()
        };
        setActiveRedeemingFulfillment(fulfillmentToActive(row2, listing));
        setRedeemingContractEndsAt(fulfillmentEndsAt(row2));
        setActiveRedeemingFulfillmentId(row2.id);
      },
      []
    );
    const applyMyRedeemingProgress = reactExports.useCallback(
      (progress2, tornXid2, listings = redeemingListingsRef.current) => {
        const myRedeem = myRedeemingFromJson(progress2);
        myRedeemingRequestRef.current = myRedeem;
        setMyRedeemingRequest(myRedeem);
        setOwnRedeemingListingIds(
          new Set(
            myRedeem ? [myRedeem.id] : listings.filter((r) => r.requesterId === tornXid2).map((r) => r.id)
          )
        );
      },
      []
    );
    const OVERLAY_TTL_MS = 45e3;
    const buyerOverlayRef = reactExports.useRef(/* @__PURE__ */ new Map());
    const redeemOverlayRef = reactExports.useRef(/* @__PURE__ */ new Map());
    const withBuyerOverlay = reactExports.useCallback(
      (fetched) => {
        const map = buyerOverlayRef.current;
        if (map.size === 0) return fetched;
        const now2 = Date.now();
        const fetchedIds = new Set(fetched.map((l) => l.id));
        for (const [id2, entry] of map) {
          if (now2 - entry.ts > OVERLAY_TTL_MS || fetchedIds.has(id2)) map.delete(id2);
        }
        if (map.size === 0) return fetched;
        return [...fetched, ...Array.from(map.values(), (e) => e.listing)];
      },
      []
    );
    const withRedeemOverlay = reactExports.useCallback(
      (fetched) => {
        const map = redeemOverlayRef.current;
        if (map.size === 0) return fetched;
        const now2 = Date.now();
        const fetchedIds = new Set(fetched.map((l) => l.id));
        for (const [id2, entry] of map) {
          if (now2 - entry.ts > OVERLAY_TTL_MS || fetchedIds.has(id2)) map.delete(id2);
        }
        if (map.size === 0) return fetched;
        return [...fetched, ...Array.from(map.values(), (e) => e.listing)];
      },
      []
    );
    const commitRedeemingList = reactExports.useCallback(
      (redeemList, tornXid2) => {
        redeemingListingsRef.current = redeemList;
        setRedeemingListings(redeemList);
        const activeFulfillment = activeRedeemingFulfillmentRowRef.current;
        if (activeFulfillment) {
          applyRedeemingFulfillment(activeFulfillment, redeemList);
        }
        if (tornXid2 != null) {
          const myRedeem = myRedeemingRequestRef.current;
          setOwnRedeemingListingIds(
            new Set(
              myRedeem ? [myRedeem.id] : redeemList.filter((r) => r.requesterId === tornXid2).map((r) => r.id)
            )
          );
        }
      },
      [applyRedeemingFulfillment]
    );
    const applyRedeemingRows = reactExports.useCallback(
      (rows, tornXid2) => {
        commitRedeemingList(
          withRedeemOverlay(rows.map(redeemingRowToListing)),
          tornXid2
        );
      },
      [commitRedeemingList, withRedeemOverlay]
    );
    const upsertBuyerOrderFromRow = reactExports.useCallback((row2) => {
      if (!(row2 == null ? void 0 : row2.id)) return;
      if (row2.status !== "open") {
        buyerOverlayRef.current.delete(row2.id);
        setMarketListings((prev) => prev.filter((l) => l.id !== row2.id));
        return;
      }
      const listing = buyerOrderRowToListing(row2);
      buyerOverlayRef.current.set(row2.id, { listing, ts: Date.now() });
      setMarketListings((prev) => {
        const idx = prev.findIndex((l) => l.id === listing.id);
        if (idx === -1) return [...prev, listing];
        const next = prev.slice();
        next[idx] = listing;
        return next;
      });
    }, []);
    const upsertRedeemingRequestFromRow = reactExports.useCallback(
      (row2, tornXid2) => {
        if (!(row2 == null ? void 0 : row2.id)) return;
        const current = redeemingListingsRef.current;
        let nextList;
        if (row2.status !== "open") {
          redeemOverlayRef.current.delete(row2.id);
          nextList = current.filter((r) => r.id !== row2.id);
        } else {
          const listing = redeemingRowToListing(row2);
          redeemOverlayRef.current.set(row2.id, { listing, ts: Date.now() });
          const idx = current.findIndex((r) => r.id === listing.id);
          if (idx === -1) {
            nextList = [...current, listing];
          } else {
            nextList = current.slice();
            nextList[idx] = listing;
          }
        }
        commitRedeemingList(nextList, tornXid2);
      },
      [commitRedeemingList]
    );
    const removeBoardListing = reactExports.useCallback((id2) => {
      buyerOverlayRef.current.delete(id2);
      redeemOverlayRef.current.delete(id2);
      setMarketListings((prev) => prev.filter((l) => l.id !== id2));
      redeemingListingsRef.current = redeemingListingsRef.current.filter(
        (r) => r.id !== id2
      );
      setRedeemingListings((prev) => prev.filter((r) => r.id !== id2));
    }, []);
    const refreshBalance = reactExports.useCallback(async () => {
      const activeSession = sessionRef.current;
      if (!configured || !activeSession) return;
      try {
        const profile = await fetchProfile(getSupabase(activeSession));
        setBalance(balanceFromProfileRow(profile));
      } catch {
      }
    }, [configured]);
    const refreshBuyerBoard = reactExports.useCallback(async () => {
      if (!configured || !loadBoardRef.current) return;
      try {
        const openOrders = (await fetchCachedBoards()).buyer;
        setMarketListings(withBuyerOverlay(openOrders.map(buyerOrderRowToListing)));
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to load buyer board");
      }
    }, [configured, withBuyerOverlay]);
    const refreshRedeemingBoard = reactExports.useCallback(async () => {
      if (!configured || !loadBoardRef.current) return;
      try {
        const activeSession = sessionRef.current;
        const redeeming = (await fetchCachedBoards()).redeeming;
        applyRedeemingRows(redeeming, activeSession == null ? void 0 : activeSession.torn_xid);
      } catch (err) {
        setError(
          err instanceof Error ? err.message : "Failed to load redeeming board"
        );
      }
    }, [configured, applyRedeemingRows]);
    const refreshBuyerBoardFresh = reactExports.useCallback(async () => {
      const activeSession = sessionRef.current;
      if (!configured || !loadBoardRef.current || !activeSession) return;
      try {
        const openOrders = await fetchOpenBuyerOrders(getSupabase(activeSession));
        setMarketListings(withBuyerOverlay(openOrders.map(buyerOrderRowToListing)));
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to load buyer board");
      }
    }, [configured, withBuyerOverlay]);
    const refreshRedeemingBoardFresh = reactExports.useCallback(async () => {
      const activeSession = sessionRef.current;
      if (!configured || !loadBoardRef.current || !activeSession) return;
      try {
        const redeeming = await fetchOpenRedeemingRequests(
          getSupabase(activeSession)
        );
        applyRedeemingRows(redeeming, activeSession.torn_xid);
      } catch (err) {
        setError(
          err instanceof Error ? err.message : "Failed to load redeeming board"
        );
      }
    }, [configured, applyRedeemingRows]);
    const refreshBuyerProgress = reactExports.useCallback(async () => {
      const activeSession = sessionRef.current;
      if (!configured || !activeSession) return;
      try {
        const progress2 = await fetchMyBuyerContractProgress(
          getSupabase(activeSession)
        );
        setBuyerOrders(buyerOrdersProgressFromJson(progress2));
      } catch (err) {
        setError(
          err instanceof Error ? err.message : "Failed to load buyer progress"
        );
      }
    }, [configured]);
    const refreshRedeemingProgress = reactExports.useCallback(async () => {
      const activeSession = sessionRef.current;
      if (!configured || !activeSession) return;
      try {
        const progress2 = await fetchMyRedeemingRequestProgress(
          getSupabase(activeSession)
        );
        applyMyRedeemingProgress(progress2, activeSession.torn_xid);
      } catch (err) {
        setError(
          err instanceof Error ? err.message : "Failed to load redeeming progress"
        );
      }
    }, [configured, applyMyRedeemingProgress]);
    const refreshActiveLossContract = reactExports.useCallback(async () => {
      const activeSession = sessionRef.current;
      if (!configured || !activeSession) return;
      try {
        const contract = await fetchMyActiveLossContract(
          getSupabase(activeSession)
        );
        applyLossContract(contract);
      } catch (err) {
        setError(
          err instanceof Error ? err.message : "Failed to load active loss contract"
        );
      }
    }, [configured, applyLossContract]);
    const refreshActiveRedeemingFulfillment = reactExports.useCallback(async () => {
      const activeSession = sessionRef.current;
      if (!configured || !activeSession) return;
      try {
        const fulfillment = await fetchMyActiveRedeemingFulfillment(
          getSupabase(activeSession)
        );
        applyRedeemingFulfillment(fulfillment, redeemingListingsRef.current);
      } catch (err) {
        setError(
          err instanceof Error ? err.message : "Failed to load active redeeming fulfillment"
        );
      }
    }, [configured, applyRedeemingFulfillment]);
    const refreshBoard = reactExports.useCallback(
      async (options) => {
        if (!configured) return;
        const silent = (options == null ? void 0 : options.silent) ?? false;
        const seq = ++boardSeqRef.current;
        if (!silent) setBoardLoading(true);
        setError(null);
        try {
          const activeSession = sessionRef.current;
          const boards = await fetchCachedBoards();
          const openOrders = boards.buyer;
          const redeeming = boards.redeeming;
          if (seq !== boardSeqRef.current) return;
          setMarketListings(withBuyerOverlay(openOrders.map(buyerOrderRowToListing)));
          const redeemList = withRedeemOverlay(redeeming.map(redeemingRowToListing));
          redeemingListingsRef.current = redeemList;
          setRedeemingListings(redeemList);
          if (guestMode) {
            setBalance(DEFAULT_USER_BALANCE);
            setBuyerOrders([]);
            setOwnRedeemingListingIds(/* @__PURE__ */ new Set());
            myRedeemingRequestRef.current = null;
            setMyRedeemingRequest(null);
            applyLossContract(null);
            applyRedeemingFulfillment(null, []);
          } else if (activeSession) {
            const myRedeem = myRedeemingRequestRef.current;
            setOwnRedeemingListingIds(
              new Set(
                myRedeem ? [myRedeem.id] : redeemList.filter((r) => r.requesterId === activeSession.torn_xid).map((r) => r.id)
              )
            );
            const activeFulfillment = activeRedeemingFulfillmentRowRef.current;
            if (activeFulfillment) {
              applyRedeemingFulfillment(activeFulfillment, redeemList);
            }
          }
          setBoardReady(true);
        } catch (err) {
          if (seq !== boardSeqRef.current) return;
          setError(err instanceof Error ? err.message : "Failed to load market board");
        } finally {
          if (!silent && seq === boardSeqRef.current) {
            setBoardLoading(false);
          }
        }
      },
      [
        configured,
        guestMode,
        applyLossContract,
        applyRedeemingFulfillment,
        applyMyRedeemingProgress,
        withBuyerOverlay,
        withRedeemOverlay
      ]
    );
    const refreshEngagement = reactExports.useCallback(
      async (options) => {
        const activeSession = sessionRef.current;
        if (!configured || !activeSession) return;
        const silent = (options == null ? void 0 : options.silent) ?? false;
        const seq = ++engagementSeqRef.current;
        if (!silent) setEngagementLoading(true);
        setError(null);
        try {
          const supabase2 = getSupabase(activeSession);
          const snap = await fetchEngagementSnapshot(supabase2);
          if (seq !== engagementSeqRef.current) return;
          setBalance(balanceFromProfileRow(snap.profile));
          setBuyerOrders(buyerOrdersProgressFromJson(snap.buyerProgress));
          applyMyRedeemingProgress(
            snap.redeemingProgress,
            activeSession.torn_xid,
            redeemingListingsRef.current
          );
          applyLossContract(snap.activeLossContract);
          applyRedeemingFulfillment(
            snap.activeRedeemingFulfillment,
            redeemingListingsRef.current
          );
        } catch (err) {
          if (seq !== engagementSeqRef.current) return;
          setError(
            err instanceof Error ? err.message : "Failed to load market data"
          );
        } finally {
          if (!silent && seq === engagementSeqRef.current) {
            setEngagementLoading(false);
            setEngagementReady(true);
          }
        }
      },
      [configured, applyLossContract, applyRedeemingFulfillment, applyMyRedeemingProgress]
    );
    const refresh = reactExports.useCallback(
      async (options) => {
        const activeSession = sessionRef.current;
        if (!configured) return;
        if (guestMode) {
          await refreshBoard(options);
          return;
        }
        if (!activeSession) return;
        if (!loadBoardRef.current) {
          await refreshEngagement(options);
          return;
        }
        const silent = (options == null ? void 0 : options.silent) ?? false;
        const seq = ++refreshSeqRef.current;
        if (!silent) {
          setEngagementLoading(true);
          setBoardLoading(true);
        }
        setError(null);
        try {
          const supabase2 = getSupabase(activeSession);
          const fresh = (options == null ? void 0 : options.fresh) ?? false;
          const [snap, boards] = await Promise.all([
            fetchEngagementSnapshot(supabase2),
            fresh ? Promise.all([
              fetchOpenBuyerOrders(supabase2),
              fetchOpenRedeemingRequests(supabase2)
            ]).then(([buyer, redeeming2]) => ({ buyer, redeeming: redeeming2 })) : fetchCachedBoards()
          ]);
          const openOrders = boards.buyer;
          const redeeming = boards.redeeming;
          if (seq !== refreshSeqRef.current) return;
          setBalance(balanceFromProfileRow(snap.profile));
          setMarketListings(withBuyerOverlay(openOrders.map(buyerOrderRowToListing)));
          setBuyerOrders(buyerOrdersProgressFromJson(snap.buyerProgress));
          const redeemList = withRedeemOverlay(redeeming.map(redeemingRowToListing));
          redeemingListingsRef.current = redeemList;
          setRedeemingListings(redeemList);
          applyMyRedeemingProgress(
            snap.redeemingProgress,
            activeSession.torn_xid,
            redeemList
          );
          applyLossContract(snap.activeLossContract);
          applyRedeemingFulfillment(snap.activeRedeemingFulfillment, redeemList);
          setBoardReady(true);
        } catch (err) {
          if (seq !== refreshSeqRef.current) return;
          setError(err instanceof Error ? err.message : "Failed to load market data");
        } finally {
          if (!silent && seq === refreshSeqRef.current) {
            setEngagementLoading(false);
            setBoardLoading(false);
            setEngagementReady(true);
          }
        }
      },
      [
        configured,
        guestMode,
        applyLossContract,
        applyRedeemingFulfillment,
        applyMyRedeemingProgress,
        refreshBoard,
        refreshEngagement,
        withBuyerOverlay,
        withRedeemOverlay
      ]
    );
    reactExports.useEffect(() => {
      if (!configured || !session) {
        setEngagementReady(true);
        return;
      }
      setEngagementReady(false);
    }, [configured, session == null ? void 0 : session.access_token, session == null ? void 0 : session.torn_xid]);
    reactExports.useEffect(() => {
      if (!configured) {
        setEngagementLoading(false);
        setEngagementReady(true);
        setBoardLoading(false);
        setBoardReady(false);
        setBalance(offlineState.balance);
        setMarketListings(offlineState.marketListings);
        setRedeemingListings(offlineState.redeemingListings);
        setBuyerOrders([]);
        setOwnRedeemingListingIds(/* @__PURE__ */ new Set());
        setMyRedeemingRequest(null);
        applyLossContract(null);
        applyRedeemingFulfillment(null, []);
        return;
      }
      if (guestMode) {
        setEngagementLoading(false);
        return;
      }
      if (!session) {
        setEngagementLoading(false);
        setBoardLoading(false);
        return;
      }
      void refreshEngagement();
    }, [
      configured,
      guestMode,
      session == null ? void 0 : session.access_token,
      session == null ? void 0 : session.torn_xid,
      refreshEngagement,
      applyLossContract,
      applyRedeemingFulfillment
    ]);
    reactExports.useEffect(() => {
      if (!configured || loadBoard) return;
      if (guestMode || useBackend) {
        clearBoardListings();
        setBoardLoading(false);
      }
    }, [configured, loadBoard, guestMode, useBackend, clearBoardListings]);
    reactExports.useEffect(() => {
      if (!configured || !loadBoard) return;
      if (guestMode) {
        void refreshBoard();
        return;
      }
      if (!session) return;
      void refreshBoard();
    }, [
      configured,
      loadBoard,
      guestMode,
      session == null ? void 0 : session.access_token,
      refreshBoard
    ]);
    reactExports.useEffect(() => {
      if (!configured || !guestMode || !loadBoard) return;
      const supabase2 = getAnonSupabase();
      const channel = supabase2.channel("market-guest").on(
        "postgres_changes",
        {
          event: "*",
          schema: "public",
          table: "buyer_orders",
          filter: "status=eq.open"
        },
        (payload) => {
          upsertBuyerOrderFromRow(payload.new);
          scheduleRefresh(refreshBuyerBoard);
        }
      ).on(
        "postgres_changes",
        {
          event: "*",
          schema: "public",
          table: "redeeming_requests",
          filter: "status=eq.open"
        },
        (payload) => {
          upsertRedeemingRequestFromRow(payload.new);
          scheduleRefresh(refreshRedeemingBoard);
        }
      ).subscribe();
      return () => {
        void supabase2.removeChannel(channel);
      };
    }, [
      configured,
      guestMode,
      loadBoard,
      refreshBuyerBoard,
      refreshRedeemingBoard,
      upsertBuyerOrderFromRow,
      upsertRedeemingRequestFromRow,
      scheduleRefresh
    ]);
    reactExports.useEffect(() => {
      if (!configured || guestMode || !session) return;
      let cancelled = false;
      const accessToken = session.access_token;
      const tornXid2 = session.torn_xid;
      const supabase2 = getSupabase(session);
      const balanceFilter = `torn_xid=eq.${tornXid2}`;
      const buyerFilter = `buyer_xid=eq.${tornXid2}`;
      const sellerFilter = `seller_xid=eq.${tornXid2}`;
      const requesterFilter = `requester_xid=eq.${tornXid2}`;
      const fulfillerFilter = `fulfiller_xid=eq.${tornXid2}`;
      const applyBalanceFromProfile = (payload) => {
        const row2 = payload.new;
        if ((row2 == null ? void 0 : row2.balance) != null) {
          setBalance(Number(row2.balance));
          return;
        }
        void refreshBalance();
      };
      const refreshOwnBuyerOrder = (payload) => {
        scheduleRefresh(refreshBuyerProgress);
        const row2 = payload.new;
        if ((row2 == null ? void 0 : row2.status) !== "open") {
          if (row2 == null ? void 0 : row2.id) buyerOverlayRef.current.delete(row2.id);
          if (loadBoardRef.current) scheduleRefresh(refreshBuyerBoardFresh);
        }
      };
      const refreshOwnLossContract = () => {
        scheduleRefresh(refreshActiveLossContract);
        scheduleRefresh(refreshBuyerProgress);
        if (loadBoardRef.current) scheduleRefresh(refreshBuyerBoardFresh);
      };
      const refreshOwnRedeemingRequest = (payload) => {
        scheduleRefresh(refreshRedeemingProgress);
        const row2 = payload.new;
        if ((row2 == null ? void 0 : row2.status) !== "open") {
          if (row2 == null ? void 0 : row2.id) redeemOverlayRef.current.delete(row2.id);
          if (loadBoardRef.current) scheduleRefresh(refreshRedeemingBoardFresh);
        }
      };
      const refreshOwnRedeemingFulfillment = () => {
        scheduleRefresh(refreshActiveRedeemingFulfillment);
        scheduleRefresh(refreshRedeemingProgress);
        if (loadBoardRef.current) scheduleRefresh(refreshRedeemingBoardFresh);
      };
      let engagementChannel = null;
      void (async () => {
        try {
          await bindRealtimeAuth(supabase2, accessToken);
          if (cancelled) return;
          engagementChannel = supabase2.channel(`market-engagement-${tornXid2}`).on(
            "postgres_changes",
            {
              event: "*",
              schema: "public",
              table: "profiles",
              filter: balanceFilter
            },
            applyBalanceFromProfile
          ).on(
            "postgres_changes",
            {
              event: "*",
              schema: "public",
              table: "buyer_orders",
              filter: buyerFilter
            },
            refreshOwnBuyerOrder
          ).on(
            "postgres_changes",
            {
              event: "*",
              schema: "public",
              table: "loss_contracts",
              filter: buyerFilter
            },
            refreshOwnLossContract
          ).on(
            "postgres_changes",
            {
              event: "*",
              schema: "public",
              table: "loss_contracts",
              filter: sellerFilter
            },
            refreshOwnLossContract
          ).on(
            "postgres_changes",
            {
              event: "*",
              schema: "public",
              table: "redeeming_requests",
              filter: requesterFilter
            },
            refreshOwnRedeemingRequest
          ).on(
            "postgres_changes",
            {
              event: "*",
              schema: "public",
              table: "redeeming_fulfillments",
              filter: requesterFilter
            },
            refreshOwnRedeemingFulfillment
          ).on(
            "postgres_changes",
            {
              event: "*",
              schema: "public",
              table: "redeeming_fulfillments",
              filter: fulfillerFilter
            },
            refreshOwnRedeemingFulfillment
          ).subscribe((status2) => {
            if (cancelled) return;
            if (status2 === "CHANNEL_ERROR" || status2 === "TIMED_OUT") {
              void refreshBalance();
            }
          });
        } catch {
          if (!cancelled) void refreshBalance();
        }
      })();
      return () => {
        cancelled = true;
        if (engagementChannel) void supabase2.removeChannel(engagementChannel);
      };
    }, [
      configured,
      guestMode,
      session == null ? void 0 : session.access_token,
      session == null ? void 0 : session.torn_xid,
      refreshBalance,
      refreshBuyerBoardFresh,
      refreshRedeemingBoardFresh,
      refreshBuyerProgress,
      refreshRedeemingProgress,
      refreshActiveLossContract,
      refreshActiveRedeemingFulfillment,
      scheduleRefresh
    ]);
    reactExports.useEffect(() => {
      if (!configured || guestMode || !session || !loadBoard) return;
      const supabase2 = getSupabase(session);
      let cancelled = false;
      let boardChannel = null;
      void (async () => {
        try {
          await bindRealtimeAuth(supabase2, session.access_token);
          if (cancelled) return;
          const boardTornXid = session.torn_xid;
          boardChannel = supabase2.channel(`market-board-${session.torn_xid}`).on(
            "postgres_changes",
            {
              event: "*",
              schema: "public",
              table: "buyer_orders",
              filter: "status=eq.open"
            },
            (payload) => {
              upsertBuyerOrderFromRow(payload.new);
              scheduleRefresh(refreshBuyerBoard);
            }
          ).on(
            "postgres_changes",
            {
              event: "*",
              schema: "public",
              table: "redeeming_requests",
              filter: "status=eq.open"
            },
            (payload) => {
              upsertRedeemingRequestFromRow(
                payload.new,
                boardTornXid
              );
              scheduleRefresh(refreshRedeemingBoard);
            }
          ).subscribe();
        } catch {
        }
      })();
      return () => {
        cancelled = true;
        if (boardChannel) void supabase2.removeChannel(boardChannel);
      };
    }, [
      configured,
      guestMode,
      loadBoard,
      session == null ? void 0 : session.access_token,
      session == null ? void 0 : session.torn_xid,
      refreshBuyerBoard,
      refreshRedeemingBoard,
      upsertBuyerOrderFromRow,
      upsertRedeemingRequestFromRow,
      scheduleRefresh
    ]);
    const tornXid = reactExports.useMemo(
      () => useBackend && session ? session.torn_xid : null,
      [useBackend, session]
    );
    const refreshAll = reactExports.useCallback(
      async (options) => {
        await refresh(options);
      },
      [refresh]
    );
    return {
      loading,
      engagementLoading,
      engagementReady,
      boardLoading: boardLoading2,
      boardReady: !loadBoard || boardReady,
      error: error2,
      balance,
      marketListings,
      buyerOrders,
      redeemingListings,
      ownRedeemingListingIds,
      myRedeemingRequest,
      activeContract,
      contractEndsAt,
      activeLossContractId,
      activeRedeemingFulfillment,
      redeemingContractEndsAt,
      activeRedeemingFulfillmentId,
      tornXid,
      refresh: refreshAll,
      refreshBalance,
      clearBuyerOrder,
      removeBoardListing,
      useBackend,
      guestMode
    };
  }
  const XANAX_MARKET_PRICE_KEY_PREFIX = "xanax_market_price_";
  function cacheKey$1(tornXid) {
    return `${XANAX_MARKET_PRICE_KEY_PREFIX}${tornXid}`;
  }
  function getUtcDateStamp(timestamp = Date.now()) {
    return new Date(timestamp).toISOString().slice(0, 10);
  }
  function getMsUntilNextUtcDate(timestamp = Date.now()) {
    const now2 = new Date(timestamp);
    const nextUtcMidnight = Date.UTC(
      now2.getUTCFullYear(),
      now2.getUTCMonth(),
      now2.getUTCDate() + 1,
      0,
      0,
      1
    );
    return Math.max(1e3, nextUtcMidnight - timestamp);
  }
  function isCachedPrice(value) {
    if (typeof value !== "object" || value === null) return false;
    const candidate = value;
    return typeof candidate.utcDate === "string" && typeof candidate.averagePrice === "number" && Number.isFinite(candidate.averagePrice) && typeof candidate.fetchedAt === "number";
  }
  async function loadCachedXanaxMarketPrice(tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(cacheKey$1(tornXid));
      return isCachedPrice(raw) ? raw : null;
    } catch {
      return null;
    }
  }
  async function saveCachedXanaxMarketPrice(tornXid, price, utcDate = getUtcDateStamp()) {
    const cached = {
      ...price,
      utcDate
    };
    await getPlatformRuntime().storage.set(cacheKey$1(tornXid), cached);
    return cached;
  }
  function useXanaxMarketPrice(session, enabled) {
    const [state, setState] = reactExports.useState(
      EMPTY_PAYOUT_CONVERSION
    );
    const [refreshTick, setRefreshTick] = reactExports.useState(0);
    const tornXid = (session == null ? void 0 : session.torn_xid) ?? null;
    reactExports.useEffect(() => {
      if (!enabled || tornXid === null) return;
      const timeoutId = window.setTimeout(() => {
        setRefreshTick((tick) => tick + 1);
      }, getMsUntilNextUtcDate());
      return () => window.clearTimeout(timeoutId);
    }, [enabled, tornXid, refreshTick]);
    reactExports.useEffect(() => {
      if (!enabled || tornXid === null) {
        setState(EMPTY_PAYOUT_CONVERSION);
        return;
      }
      let cancelled = false;
      const today = getUtcDateStamp();
      void (async () => {
        const [cachedPrice, permissions] = await Promise.all([
          loadCachedXanaxMarketPrice(tornXid),
          loadTornApiPermissionsCache(tornXid)
        ]);
        if (cancelled) return;
        const cacheValidToday = (cachedPrice == null ? void 0 : cachedPrice.utcDate) === today;
        const itemMarketVerified = isTornApiPermissionVerified(
          permissions,
          "itemMarket"
        );
        if (cachedPrice) {
          setState({
            price: cachedPrice,
            loading: !(cacheValidToday && itemMarketVerified),
            error: null,
            permissionError: false
          });
        } else {
          setState({
            ...EMPTY_PAYOUT_CONVERSION,
            loading: true
          });
        }
        if (cacheValidToday && itemMarketVerified) {
          return;
        }
        try {
          const price = await getPlatformRuntime().tornMarket.fetchXanaxMarketPrice();
          const saved2 = await saveCachedXanaxMarketPrice(tornXid, price, today);
          await setTornApiPermissionVerified(tornXid, "itemMarket");
          if (cancelled) return;
          setState({
            price: saved2,
            loading: false,
            error: null,
            permissionError: false
          });
        } catch (err) {
          if (cancelled) return;
          const permissionError = isTornMarketPermissionError(err);
          setState({
            price: permissionError ? null : cachedPrice,
            loading: false,
            error: err instanceof Error ? err.message : "Could not load Torn Xanax market price.",
            permissionError
          });
        }
      })();
      return () => {
        cancelled = true;
      };
    }, [enabled, tornXid, refreshTick]);
    return state;
  }
  function useTornItemReceiveLogPermission(session, enabled) {
    const [permissionError, setPermissionError] = reactExports.useState(false);
    const tornXid = (session == null ? void 0 : session.torn_xid) ?? null;
    reactExports.useEffect(() => {
      if (!enabled || tornXid === null) {
        setPermissionError(false);
        return;
      }
      let cancelled = false;
      void (async () => {
        const cached = await loadTornApiPermissionsCache(tornXid);
        if (cancelled) return;
        if (isTornApiPermissionVerified(cached, "itemReceiveLog")) {
          setPermissionError(false);
          return;
        }
        try {
          await getPlatformRuntime().tornMarket.assertItemReceiveLogAccess();
          await setTornApiPermissionVerified(tornXid, "itemReceiveLog");
          if (cancelled) return;
          setPermissionError(false);
        } catch (err) {
          if (cancelled) return;
          setPermissionError(isTornLogPermissionError(err));
        }
      })();
      return () => {
        cancelled = true;
      };
    }, [enabled, tornXid]);
    return permissionError;
  }
  function useTornEquipmentPermission(session, enabled) {
    const [permissionError, setPermissionError] = reactExports.useState(false);
    const tornXid = (session == null ? void 0 : session.torn_xid) ?? null;
    reactExports.useEffect(() => {
      if (!enabled || tornXid === null) {
        setPermissionError(false);
        return;
      }
      let cancelled = false;
      void (async () => {
        const cached = await loadTornApiPermissionsCache(tornXid);
        if (cancelled) return;
        if (isTornApiPermissionVerified(cached, "equipment")) {
          setPermissionError(false);
          return;
        }
        try {
          const platform = getPlatformRuntime();
          const apiKey = await platform.auth.getApiKey();
          if (!apiKey) {
            if (!cancelled) setPermissionError(false);
            return;
          }
          await platform.tornMarket.fetchUserEquipment();
          await setTornApiPermissionVerified(tornXid, "equipment");
          if (!cancelled) setPermissionError(false);
        } catch (err) {
          if (cancelled) return;
          setPermissionError(isTornEquipmentPermissionError(err));
        }
      })();
      return () => {
        cancelled = true;
      };
    }, [enabled, tornXid]);
    return permissionError;
  }
  async function fetchFactionMemberIds(factionId, apiKey) {
    const url = `https://api.torn.com/faction/${factionId}?selections=basic&key=${encodeURIComponent(
      apiKey
    )}`;
    let res;
    try {
      res = await fetch(url);
    } catch {
      throw new Error("Network error contacting the Torn API.");
    }
    if (!res.ok) {
      throw new Error(`Torn API request failed (${res.status}).`);
    }
    let data;
    try {
      data = await res.json();
    } catch {
      throw new Error("Could not parse the Torn API response.");
    }
    if (data.error) {
      throw new Error(data.error.error || "Torn API error.");
    }
    const members = data.members ?? {};
    const ids = Object.keys(members).map((id2) => Number(id2)).filter((id2) => Number.isFinite(id2) && id2 > 0);
    return ids;
  }
  function normalizeState(state) {
    return state.trim().toLowerCase();
  }
  function isInHospital(state) {
    return normalizeState(state) === "hospital";
  }
  function isTraveling(state) {
    return normalizeState(state) === "traveling";
  }
  async function fetchTornTargetStatus(targetId, apiKey, fetchImpl = fetch) {
    var _a2, _b, _c, _d;
    const trimmedKey = apiKey.trim();
    if (!trimmedKey) {
      throw new Error("Torn API key is missing.");
    }
    const url = new URL(`https://api.torn.com/user/${targetId}`);
    url.searchParams.set("selections", "");
    url.searchParams.set("key", trimmedKey);
    const response = await fetchImpl(url.href, { method: "GET" });
    const raw = await response.text();
    let payload;
    try {
      payload = typeof raw === "string" && raw.length > 0 ? JSON.parse(raw) : {};
    } catch {
      throw new Error(
        `Torn user status returned invalid JSON (HTTP ${response.status}).`
      );
    }
    if (!response.ok || payload.error) {
      const message = typeof ((_a2 = payload.error) == null ? void 0 : _a2.error) === "string" ? payload.error.error : `HTTP ${response.status}`;
      throw new Error(`Torn user status failed: ${message}`);
    }
    const state = ((_b = payload.status) == null ? void 0 : _b.state) ?? "Okay";
    const description2 = ((_c = payload.status) == null ? void 0 : _c.description) ?? "";
    const inHospital = isInHospital(state);
    const traveling = isTraveling(state);
    return {
      playerId: payload.player_id ?? targetId,
      name: typeof payload.name === "string" ? payload.name : null,
      state,
      description: description2,
      until: typeof ((_d = payload.status) == null ? void 0 : _d.until) === "number" ? payload.status.until : 0,
      inHospital,
      traveling,
      hittable: !inHospital && !traveling
    };
  }
  async function verifyActiveFulfillment(accessToken, kind, id2, apiKey) {
    const functionName = kind === "loss" ? "poll_loss_contract" : kind === "redeem" ? "poll_redeem_fulfillment" : "poll_bounty_contract";
    const body2 = kind === "loss" ? { contract_id: id2, api_key: apiKey } : kind === "redeem" ? { fulfillment_id: id2, api_key: apiKey } : { contract_id: id2, api_key: apiKey };
    const platformFetch = getPlatformRuntime().fetch ?? fetch;
    const res = await platformFetch(`${SUPABASE_URL}/functions/v1/${functionName}`, {
      method: "POST",
      cache: "no-store",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${accessToken}`,
        apikey: SUPABASE_ANON_KEY
      },
      body: JSON.stringify(body2)
    });
    const raw = await res.text();
    let data;
    try {
      data = JSON.parse(raw);
    } catch {
      throw new Error(
        `Verification failed (${res.status}): invalid response from server`
      );
    }
    throwIfPollVerifyFailed(res.status, data);
    return data;
  }
  function isFulfillmentCompleted(result) {
    if ("contract" in result) {
      return result.contract.status === "completed";
    }
    return result.fulfillment.status === "completed";
  }
  function isFulfillmentTerminal(result) {
    if ("contract" in result) {
      return result.contract.status !== "active";
    }
    return result.fulfillment.status !== "active";
  }
  function isRenderableLossContract(contract) {
    if (!contract) return false;
    return contract.quantity > 0 && contract.listing.sellerId > 0;
  }
  function isRenderableRedeemFulfillment(fulfillment) {
    if (!fulfillment) return false;
    return fulfillment.xanaxTotal > 0 && fulfillment.listing.requesterId > 0;
  }
  const STORAGE_KEY_PREFIX$4 = "dismissed_buyer_orders_";
  function storageKey$4(tornXid) {
    return tornXid == null ? `${STORAGE_KEY_PREFIX$4}guest` : `${STORAGE_KEY_PREFIX$4}${tornXid}`;
  }
  function parseIds$2(raw) {
    if (typeof raw === "string") {
      try {
        return parseIds$2(JSON.parse(raw));
      } catch {
        return [];
      }
    }
    if (!Array.isArray(raw)) return [];
    return raw.filter((id2) => typeof id2 === "string");
  }
  function readIdsSync$2(tornXid) {
    try {
      const raw = readLocalStorageWithMigration(localStorage, storageKey$4(tornXid));
      if (raw == null) return /* @__PURE__ */ new Set();
      const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
      return new Set(parseIds$2(parsed));
    } catch {
      return /* @__PURE__ */ new Set();
    }
  }
  function writeIdsSync$2(tornXid, ids) {
    try {
      writeLocalStorageCurrent(
        localStorage,
        storageKey$4(tornXid),
        JSON.stringify([...ids])
      );
    } catch {
    }
  }
  function readDismissedBuyerOrderIds(tornXid) {
    return readIdsSync$2(tornXid);
  }
  function dismissBuyerOrder(tornXid, orderId) {
    const ids = readIdsSync$2(tornXid);
    ids.add(orderId);
    writeIdsSync$2(tornXid, ids);
    return ids;
  }
  function pruneDismissedBuyerOrderIds(tornXid, knownOrderIds) {
    const stored = readIdsSync$2(tornXid);
    if (knownOrderIds.size === 0) return stored;
    const pruned = new Set([...stored].filter((id2) => knownOrderIds.has(id2)));
    if (pruned.size !== stored.size) {
      writeIdsSync$2(tornXid, pruned);
    }
    return pruned;
  }
  const STORAGE_KEY_PREFIX$3 = "dismissed_references_";
  function storageKey$3(tornXid) {
    return tornXid == null ? `${STORAGE_KEY_PREFIX$3}guest` : `${STORAGE_KEY_PREFIX$3}${tornXid}`;
  }
  function parseIds$1(raw) {
    if (typeof raw === "string") {
      try {
        return parseIds$1(JSON.parse(raw));
      } catch {
        return [];
      }
    }
    if (!Array.isArray(raw)) return [];
    return raw.filter((id2) => typeof id2 === "string");
  }
  function readIdsSync$1(tornXid) {
    try {
      const raw = readLocalStorageWithMigration(localStorage, storageKey$3(tornXid));
      if (raw == null) return /* @__PURE__ */ new Set();
      const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
      return new Set(parseIds$1(parsed));
    } catch {
      return /* @__PURE__ */ new Set();
    }
  }
  function writeIdsSync$1(tornXid, ids) {
    try {
      writeLocalStorageCurrent(
        localStorage,
        storageKey$3(tornXid),
        JSON.stringify([...ids])
      );
    } catch {
    }
  }
  function readDismissedReferencesIds(tornXid) {
    return readIdsSync$1(tornXid);
  }
  function dismissReferences(tornXid, orderId) {
    const ids = readIdsSync$1(tornXid);
    ids.add(orderId);
    writeIdsSync$1(tornXid, ids);
    return ids;
  }
  function undismissReferences(tornXid, orderId) {
    const ids = readIdsSync$1(tornXid);
    ids.delete(orderId);
    writeIdsSync$1(tornXid, ids);
    return ids;
  }
  function pruneDismissedReferencesIds(tornXid, knownOrderIds) {
    const stored = readIdsSync$1(tornXid);
    if (knownOrderIds.size === 0) return stored;
    const pruned = new Set([...stored].filter((id2) => knownOrderIds.has(id2)));
    if (pruned.size !== stored.size) {
      writeIdsSync$1(tornXid, pruned);
    }
    return pruned;
  }
  const STORAGE_KEY_PREFIX$2 = "dismissed_bounty_reveal_";
  function storageKey$2(tornXid) {
    return tornXid == null ? `${STORAGE_KEY_PREFIX$2}guest` : `${STORAGE_KEY_PREFIX$2}${tornXid}`;
  }
  function parseIds(raw) {
    if (typeof raw === "string") {
      try {
        return parseIds(JSON.parse(raw));
      } catch {
        return [];
      }
    }
    if (!Array.isArray(raw)) return [];
    return raw.filter((id2) => typeof id2 === "string");
  }
  function readIdsSync(tornXid) {
    try {
      const raw = readLocalStorageWithMigration(localStorage, storageKey$2(tornXid));
      if (raw == null) return /* @__PURE__ */ new Set();
      const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
      return new Set(parseIds(parsed));
    } catch {
      return /* @__PURE__ */ new Set();
    }
  }
  function writeIdsSync(tornXid, ids) {
    try {
      writeLocalStorageCurrent(
        localStorage,
        storageKey$2(tornXid),
        JSON.stringify([...ids])
      );
    } catch {
    }
  }
  function readDismissedBountyRevealIds(tornXid) {
    return readIdsSync(tornXid);
  }
  function dismissBountyReveal(tornXid, orderId) {
    const ids = readIdsSync(tornXid);
    ids.add(orderId);
    writeIdsSync(tornXid, ids);
    return ids;
  }
  function undismissBountyReveal(tornXid, orderId) {
    const ids = readIdsSync(tornXid);
    ids.delete(orderId);
    writeIdsSync(tornXid, ids);
    return ids;
  }
  function pruneDismissedBountyRevealIds(tornXid, knownOrderIds) {
    const stored = readIdsSync(tornXid);
    if (knownOrderIds.size === 0) return stored;
    const pruned = new Set([...stored].filter((id2) => knownOrderIds.has(id2)));
    if (pruned.size !== stored.size) {
      writeIdsSync(tornXid, pruned);
    }
    return pruned;
  }
  function isTakeableLossListing(listing) {
    return listing.quantity > 0;
  }
  function isTakeableRedeemingListing(listing) {
    return listing.quantity > 0;
  }
  function listingMatchesMarketAlert(listing, contractType, threshold, ownListingIds) {
    return listing.contractType === contractType && !ownListingIds.has(listing.id) && isTakeableLossListing(listing) && listing.payPerLoss >= threshold;
  }
  function listingMatchesWithdrawalAlert(listing, threshold, ownListingIds) {
    return !ownListingIds.has(listing.id) && isTakeableRedeemingListing(listing) && listing.quantity >= threshold;
  }
  function getMatchingMarketAlertKeys(listings, contractType, threshold, ownListingIds) {
    return listings.filter(
      (l) => listingMatchesMarketAlert(l, contractType, threshold, ownListingIds)
    ).map((l) => `${contractType}:${l.id}`);
  }
  function getMatchingWithdrawalAlertKeys(listings, threshold, ownListingIds) {
    return listings.filter((l) => listingMatchesWithdrawalAlert(l, threshold, ownListingIds)).map((l) => `redeem:${l.id}`);
  }
  function isTakeableBountyOrder(order) {
    return order.status === "open" && order.quantityRemaining > 0;
  }
  function bountyOrderMatchesAlert(order, threshold, ownOrderIds) {
    return !ownOrderIds.has(order.id) && isTakeableBountyOrder(order) && order.quantityRemaining >= threshold;
  }
  function getMatchingBountyAlertKeys(orders, threshold, ownOrderIds) {
    return orders.filter((o) => bountyOrderMatchesAlert(o, threshold, ownOrderIds)).map((o) => `bounty:${o.id}`);
  }
  function embargoMatchesAlert(embargo, threshold, ownIds) {
    return !ownIds.has(embargo.id) && embargo.status === "open" && embargo.escrowedPts >= threshold;
  }
  function getMatchingEmbargoAlertKeys(embargos, threshold, ownIds) {
    return embargos.filter((e) => embargoMatchesAlert(e, threshold, ownIds)).map((e) => `embargo:${e.id}`);
  }
  function productivityBoostMatchesAlert(boost, threshold, ownIds) {
    return !ownIds.has(boost.id) && boost.status === "open" && boost.escrowedPts >= threshold;
  }
  function getMatchingProductivityAlertKeys(boosts, threshold, ownIds) {
    return boosts.filter((b) => productivityBoostMatchesAlert(b, threshold, ownIds)).map((b) => `productivity:${b.id}`);
  }
  function flightDelayMatchesAlert(flightDelay, threshold, ownIds) {
    return !ownIds.has(flightDelay.id) && flightDelay.status === "open" && flightDelay.escrowedPts >= threshold;
  }
  function getMatchingFlightDelayAlertKeys(flightDelays, threshold, ownIds) {
    return flightDelays.filter((f) => flightDelayMatchesAlert(f, threshold, ownIds)).map((f) => `flight-delay:${f.id}`);
  }
  function computeMarketAlertHighlights(marketListings, redeemingListings, thresholds2, ownListingIds, ownRedeemingListingIds, bountyOrders = [], ownBountyOrderIds = /* @__PURE__ */ new Set(), embargos = [], ownEmbargoIds = /* @__PURE__ */ new Set(), productivityBoosts = [], ownProductivityIds = /* @__PURE__ */ new Set(), flightDelays = [], ownFlightDelayIds = /* @__PURE__ */ new Set(), simpleServices = [], ownSimpleServiceIds = /* @__PURE__ */ new Set()) {
    const matchingKeys = [];
    const contractTypeAlerts = /* @__PURE__ */ new Set();
    const matchingCounts = {};
    const alertingOtherSubtypes = /* @__PURE__ */ new Set();
    for (const contractType of CONTRACT_TYPES) {
      const threshold = thresholds2[contractType];
      if (threshold === null) continue;
      const keys = getMatchingMarketAlertKeys(
        marketListings,
        contractType,
        threshold,
        ownListingIds
      );
      if (keys.length > 0) {
        contractTypeAlerts.add(contractType);
        matchingKeys.push(...keys);
        matchingCounts[contractType] = keys.length;
      }
    }
    const withdrawalKeys = thresholds2.withdrawal !== null ? getMatchingWithdrawalAlertKeys(
      redeemingListings,
      thresholds2.withdrawal,
      ownRedeemingListingIds
    ) : [];
    matchingKeys.push(...withdrawalKeys);
    const bountyKeys = thresholds2.bounty !== null ? getMatchingBountyAlertKeys(
      bountyOrders,
      thresholds2.bounty,
      ownBountyOrderIds
    ) : [];
    matchingKeys.push(...bountyKeys);
    const embargoKeys = thresholds2.embargo !== null ? getMatchingEmbargoAlertKeys(
      embargos,
      thresholds2.embargo,
      ownEmbargoIds
    ) : [];
    matchingKeys.push(...embargoKeys);
    const productivityKeys = thresholds2.productivity !== null ? getMatchingProductivityAlertKeys(
      productivityBoosts,
      thresholds2.productivity,
      ownProductivityIds
    ) : [];
    matchingKeys.push(...productivityKeys);
    const flightDelayKeys = thresholds2.flightDelay !== null ? getMatchingFlightDelayAlertKeys(
      flightDelays,
      thresholds2.flightDelay,
      ownFlightDelayIds
    ) : [];
    matchingKeys.push(...flightDelayKeys);
    const simpleServiceKeys = [];
    const simpleServiceCountByKind = {};
    for (const service of simpleServices) {
      if (ownSimpleServiceIds.has(service.id) || service.status !== "open") {
        continue;
      }
      const threshold = thresholds2.simpleServices[service.kind];
      if (threshold != null && service.escrowedPts >= threshold) {
        simpleServiceKeys.push(`simple-service:${service.id}`);
        simpleServiceCountByKind[service.kind] = (simpleServiceCountByKind[service.kind] ?? 0) + 1;
      }
    }
    matchingKeys.push(...simpleServiceKeys);
    const withdrawalAlertActive = withdrawalKeys.length > 0;
    const bountyAlertActive = bountyKeys.length > 0;
    const embargoAlertActive = embargoKeys.length > 0;
    const productivityAlertActive = productivityKeys.length > 0;
    const flightDelayAlertActive = flightDelayKeys.length > 0;
    const simpleServiceAlertActive = simpleServiceKeys.length > 0;
    if (withdrawalAlertActive) matchingCounts.withdrawals = withdrawalKeys.length;
    if (bountyAlertActive) matchingCounts.bounties = bountyKeys.length;
    if (embargoAlertActive) {
      matchingCounts.embargo = embargoKeys.length;
      alertingOtherSubtypes.add("embargo");
    }
    if (productivityAlertActive) {
      matchingCounts.productivity = productivityKeys.length;
      alertingOtherSubtypes.add("productivity-boost");
    }
    if (flightDelayAlertActive) {
      matchingCounts["flight-delay"] = flightDelayKeys.length;
      alertingOtherSubtypes.add("flight-delay");
    }
    for (const [kind, count] of Object.entries(simpleServiceCountByKind)) {
      if (count && count > 0) {
        matchingCounts[`simple-${kind}`] = count;
        alertingOtherSubtypes.add(kind);
      }
    }
    return {
      sellModeAlert: contractTypeAlerts.size > 0,
      redeemingModeAlert: withdrawalAlertActive || bountyAlertActive || embargoAlertActive || productivityAlertActive || flightDelayAlertActive || simpleServiceAlertActive,
      withdrawalAlertActive,
      bountyAlertActive,
      embargoAlertActive,
      productivityAlertActive,
      flightDelayAlertActive,
      simpleServiceAlertActive,
      contractTypeAlerts,
      matchingKeys,
      matchingCounts,
      alertingOtherSubtypes
    };
  }
  const STORAGE_KEY$b = "bln:alert-dedupe";
  const DEDUPE_TTL_MS = 4e3;
  const LOCK_NAME = "bln-alert-sound";
  function signatureFor(newKeys) {
    return newKeys.slice().sort().join("|");
  }
  function readMap() {
    try {
      const raw = window.localStorage.getItem(STORAGE_KEY$b);
      if (!raw) return {};
      const parsed = JSON.parse(raw);
      return parsed && typeof parsed === "object" ? parsed : {};
    } catch {
      return {};
    }
  }
  function claim(sig, now2) {
    const map = readMap();
    const last = map[sig];
    if (last != null && now2 - last < DEDUPE_TTL_MS) return false;
    const next = { [sig]: now2 };
    for (const [key, ts] of Object.entries(map)) {
      if (key !== sig && now2 - ts < DEDUPE_TTL_MS) next[key] = ts;
    }
    try {
      window.localStorage.setItem(STORAGE_KEY$b, JSON.stringify(next));
    } catch {
    }
    return true;
  }
  async function playMarketAlertSoundDeduped(newKeys, volumePercent) {
    if (newKeys.length === 0) return;
    const sig = signatureFor(newKeys);
    if (typeof window === "undefined" || !window.localStorage) {
      playLossMarketAlertSound(volumePercent);
      return;
    }
    const now2 = Date.now();
    const locks = navigator.locks;
    if (locks == null ? void 0 : locks.request) {
      let won = false;
      try {
        await locks.request(LOCK_NAME, { mode: "exclusive" }, async () => {
          won = claim(sig, now2);
        });
      } catch {
        won = claim(sig, now2);
      }
      if (won) playLossMarketAlertSound(volumePercent);
      return;
    }
    if (claim(sig, now2)) playLossMarketAlertSound(volumePercent);
  }
  function overlayMouseDownDismiss(event, onDismiss) {
    if (event.target === event.currentTarget) onDismiss();
  }
  const STORAGE_KEY$a = "first_contract_completed";
  async function hasFirstContractCompleted() {
    try {
      return await getPlatformRuntime().storage.get(STORAGE_KEY$a) === true;
    } catch {
      return false;
    }
  }
  async function markFirstContractCompleted() {
    try {
      await getPlatformRuntime().storage.set(STORAGE_KEY$a, true);
    } catch {
    }
  }
  let audience = "default";
  function getCampaignAudience() {
    return audience;
  }
  const GO_SELL_ATTACKS_KEY = "seller_go_sell_attacks_seen";
  const TAKE_CONTRACT_KEY = "seller_take_contract_seen";
  async function getFlag(key) {
    try {
      return await getPlatformRuntime().storage.get(key) === true;
    } catch {
      return false;
    }
  }
  async function setFlag(key) {
    try {
      await getPlatformRuntime().storage.set(key, true);
    } catch {
    }
  }
  const hasSeenSellerGoSellAttacks = () => getFlag(GO_SELL_ATTACKS_KEY);
  const markSellerGoSellAttacksSeen = () => setFlag(GO_SELL_ATTACKS_KEY);
  const hasSeenSellerTakeContract = () => getFlag(TAKE_CONTRACT_KEY);
  const MOUNT_SELECTOR = "[data-tlm-mount]";
  function getExtensionShadowMount() {
    var _a2;
    const host = document.getElementById(CONTENT_HOST_ID) ?? document.getElementById(LEGACY_CONTENT_HOST_ID);
    return ((_a2 = host == null ? void 0 : host.shadowRoot) == null ? void 0 : _a2.querySelector(MOUNT_SELECTOR)) ?? null;
  }
  function useSpotlightFade(visible) {
    const [opacity, setOpacity] = reactExports.useState(0);
    reactExports.useEffect(() => {
      if (!visible) {
        setOpacity(0);
        return;
      }
      const id2 = requestAnimationFrame(() => {
        requestAnimationFrame(() => setOpacity(1));
      });
      return () => cancelAnimationFrame(id2);
    }, [visible]);
    return opacity;
  }
  var reactDomExports = requireReactDom();
  const SETTLE_POLL_MS = 600;
  function rectsEqual(a, b) {
    return a !== null && a.left === b.left && a.top === b.top && a.width === b.width && a.height === b.height;
  }
  function getLayoutObserveTargets(el) {
    const targets = /* @__PURE__ */ new Set([el]);
    const parent = el.parentElement;
    if (parent) targets.add(parent);
    const form2 = el.closest("form");
    if (form2) targets.add(form2);
    return [...targets];
  }
  function useElementViewportRect(ref, active, layoutKey) {
    const [rect, setRect] = reactExports.useState(null);
    reactExports.useLayoutEffect(() => {
      if (!active) {
        setRect(null);
        return;
      }
      let ro = null;
      let observedEl = null;
      const attachObservers = (el) => {
        if (observedEl === el) return;
        ro == null ? void 0 : ro.disconnect();
        observedEl = el;
        ro = new ResizeObserver(update);
        for (const target2 of getLayoutObserveTargets(el)) {
          ro.observe(target2);
        }
      };
      const update = () => {
        const el = ref.current;
        if (!el) {
          if (observedEl) {
            ro == null ? void 0 : ro.disconnect();
            ro = null;
            observedEl = null;
          }
          setRect(null);
          return;
        }
        attachObservers(el);
        const next = el.getBoundingClientRect();
        setRect((prev) => rectsEqual(prev, next) ? prev : next);
      };
      update();
      window.addEventListener("resize", update);
      window.addEventListener("scroll", update, true);
      document.addEventListener("transitionend", update, true);
      document.addEventListener("animationend", update, true);
      const start = performance.now();
      let rafId = 0;
      const poll = () => {
        update();
        if (performance.now() - start < SETTLE_POLL_MS) {
          rafId = requestAnimationFrame(poll);
        }
      };
      rafId = requestAnimationFrame(poll);
      return () => {
        cancelAnimationFrame(rafId);
        ro == null ? void 0 : ro.disconnect();
        window.removeEventListener("resize", update);
        window.removeEventListener("scroll", update, true);
        document.removeEventListener("transitionend", update, true);
        document.removeEventListener("animationend", update, true);
      };
    }, [ref, active, layoutKey]);
    return rect;
  }
  let lockCount = 0;
  let saved$1 = null;
  let touchMoveBlocker = null;
  function blockTouchMove(e) {
    if (e.touches.length > 1) return;
    if (e.cancelable) e.preventDefault();
  }
  function lockBackgroundScroll() {
    if (typeof document === "undefined") return () => {
    };
    let released = false;
    if (lockCount === 0) {
      const html = document.documentElement;
      const body2 = document.body;
      if (!body2) {
        lockCount = 1;
        return () => {
          lockCount = 0;
        };
      }
      const scrollX = window.scrollX;
      const scrollY = window.scrollY;
      saved$1 = {
        bodyPosition: body2.style.position,
        bodyTop: body2.style.top,
        bodyLeft: body2.style.left,
        bodyRight: body2.style.right,
        bodyWidth: body2.style.width,
        bodyOverflow: body2.style.overflow,
        htmlOverflow: html.style.overflow,
        bodyOverscroll: body2.style.overscrollBehavior,
        htmlOverscroll: html.style.overscrollBehavior,
        scrollX,
        scrollY
      };
      body2.style.position = "fixed";
      body2.style.top = `-${scrollY}px`;
      body2.style.left = `-${scrollX}px`;
      body2.style.right = "0";
      body2.style.width = "100%";
      body2.style.overflow = "hidden";
      html.style.overflow = "hidden";
      body2.style.overscrollBehavior = "none";
      html.style.overscrollBehavior = "none";
      touchMoveBlocker = blockTouchMove;
      document.addEventListener("touchmove", touchMoveBlocker, { passive: false });
    }
    lockCount += 1;
    return () => {
      if (released) return;
      released = true;
      lockCount = Math.max(0, lockCount - 1);
      if (lockCount > 0 || !saved$1) return;
      const html = document.documentElement;
      const body2 = document.body;
      const { scrollX, scrollY } = saved$1;
      if (body2) {
        body2.style.position = saved$1.bodyPosition;
        body2.style.top = saved$1.bodyTop;
        body2.style.left = saved$1.bodyLeft;
        body2.style.right = saved$1.bodyRight;
        body2.style.width = saved$1.bodyWidth;
        body2.style.overflow = saved$1.bodyOverflow;
        body2.style.overscrollBehavior = saved$1.bodyOverscroll;
      }
      html.style.overflow = saved$1.htmlOverflow;
      html.style.overscrollBehavior = saved$1.htmlOverscroll;
      saved$1 = null;
      if (touchMoveBlocker) {
        document.removeEventListener("touchmove", touchMoveBlocker);
        touchMoveBlocker = null;
      }
      window.scrollTo(scrollX, scrollY);
    };
  }
  const DEFAULT_SPOTLIGHT_Z = 2147483646;
  const EXTENSION_SPOTLIGHT_Z = 2147483647;
  const API_KEY_SPOTLIGHT_Z = 2147483651;
  const DIM_ALPHA = 0.72;
  const SHADOW_SPREAD_PX = 9999;
  const SPOTLIGHT_PAD_PX = 2;
  const PULSE_DURATION_MS = 1600;
  function PanelButtonTutorial({
    visible,
    opacity,
    fadeMs,
    targetRef,
    onTransitionEnd,
    portalTarget = document.body,
    layerZIndex = DEFAULT_SPOTLIGHT_Z,
    layoutKey,
    onDarknessClick,
    caption,
    captionWidth = 320
  }) {
    const rect = useElementViewportRect(targetRef, visible, layoutKey);
    const holeRef = reactExports.useRef(null);
    const [vvOffset, setVvOffset] = reactExports.useState({ top: 0, left: 0 });
    reactExports.useEffect(() => {
      if (!visible) return;
      const vv = window.visualViewport;
      if (!vv) return;
      const sync = () => setVvOffset({ top: vv.offsetTop, left: vv.offsetLeft });
      sync();
      vv.addEventListener("resize", sync);
      vv.addEventListener("scroll", sync);
      return () => {
        vv.removeEventListener("resize", sync);
        vv.removeEventListener("scroll", sync);
      };
    }, [visible]);
    reactExports.useEffect(() => {
      if (!visible) return;
      const release = lockBackgroundScroll();
      return release;
    }, [visible]);
    reactExports.useEffect(() => {
      if (!visible) return;
      const el = holeRef.current;
      if (!el || typeof el.animate !== "function") return;
      const animation = el.animate(
        [
          {
            outlineWidth: "0px",
            outlineColor: "rgba(255, 255, 255, 0)",
            outlineOffset: "0px"
          },
          {
            outlineWidth: "3px",
            outlineColor: "rgba(255, 255, 255, 0.9)",
            outlineOffset: "4px"
          },
          {
            outlineWidth: "0px",
            outlineColor: "rgba(255, 255, 255, 0)",
            outlineOffset: "0px"
          }
        ],
        {
          duration: PULSE_DURATION_MS,
          iterations: Infinity,
          easing: "ease-in-out"
        }
      );
      return () => animation.cancel();
    }, [visible, rect == null ? void 0 : rect.left, rect == null ? void 0 : rect.top, rect == null ? void 0 : rect.width, rect == null ? void 0 : rect.height]);
    if (!visible || !rect) return null;
    const pad = SPOTLIGHT_PAD_PX;
    const left = rect.left - pad + vvOffset.left;
    const top = rect.top - pad + vvOffset.top;
    const width = rect.width + pad * 2;
    const height = rect.height + pad * 2;
    const wrapperStyle = {
      position: "fixed",
      inset: 0,
      zIndex: layerZIndex,
      pointerEvents: "none",
      opacity,
      transition: `opacity ${fadeMs}ms ease`
    };
    const holeStyle = {
      position: "fixed",
      left,
      top,
      width,
      height,
      borderRadius: 4,
      pointerEvents: "none",
      outlineStyle: "solid",
      outlineWidth: 0,
      outlineColor: "rgba(255, 255, 255, 0)",
      outlineOffset: 0,
      boxShadow: `0 0 0 ${SHADOW_SPREAD_PX}px rgba(0, 0, 0, ${DIM_ALPHA})`
    };
    const captionBelow = top + height + 140 <= window.innerHeight;
    const captionMaxWidth = Math.min(captionWidth, window.innerWidth * 0.9);
    const captionMargin = 8;
    const captionCenterX = Math.min(
      Math.max(left + width / 2, captionMaxWidth / 2 + captionMargin),
      window.innerWidth - captionMaxWidth / 2 - captionMargin
    );
    const captionStyle = {
      position: "fixed",
      left: captionCenterX,
      top: captionBelow ? top + height + 12 : top - 12,
      transform: captionBelow ? "translateX(-50%)" : "translate(-50%, -100%)",
      width: captionMaxWidth,
      maxWidth: "90vw",
      textAlign: "center",
      pointerEvents: "none"
    };
    if (!portalTarget) return null;
    const shuttersActive = Boolean(onDarknessClick) && opacity > 0;
    const shutterBase = {
      position: "fixed",
      pointerEvents: shuttersActive ? "auto" : "none"
    };
    const shutters = [
      { ...shutterBase, left: 0, right: 0, top: 0, height: Math.max(0, top) },
      { ...shutterBase, left: 0, right: 0, top: top + height, bottom: 0 },
      { ...shutterBase, left: 0, width: Math.max(0, left), top, height },
      { ...shutterBase, left: left + width, right: 0, top, height }
    ];
    return reactDomExports.createPortal(
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          role: "presentation",
          style: wrapperStyle,
          onTransitionEnd: (e) => onTransitionEnd(e.propertyName),
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ref: holeRef, style: holeStyle }),
            caption ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: captionStyle, children: caption }) : null,
            onDarknessClick && shutters.map((style, i) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                role: "presentation",
                style,
                onMouseDown: onDarknessClick
              },
              i
            ))
          ]
        }
      ),
      portalTarget
    );
  }
  const overlay$1 = "_overlay_1nw3y_1";
  const overlayElevated = "_overlayElevated_1nw3y_16";
  const overlayElevatedTop = "_overlayElevatedTop_1nw3y_20";
  const dialog$5 = "_dialog_1nw3y_24";
  const title$4 = "_title_1nw3y_35";
  const walletHeader = "_walletHeader_1nw3y_43";
  const infoButton = "_infoButton_1nw3y_54";
  const infoPopover = "_infoPopover_1nw3y_80";
  const introBanner = "_introBanner_1nw3y_101";
  const introText = "_introText_1nw3y_113";
  const introDismiss = "_introDismiss_1nw3y_126";
  const tabs = "_tabs_1nw3y_142";
  const tab = "_tab_1nw3y_142";
  const tabActive = "_tabActive_1nw3y_172";
  const trustNote = "_trustNote_1nw3y_181";
  const depositRedirect = "_depositRedirect_1nw3y_188";
  const summarySub = "_summarySub_1nw3y_199";
  const subtitle = "_subtitle_1nw3y_207";
  const label$2 = "_label_1nw3y_214";
  const input$3 = "_input_1nw3y_224";
  const inputWrap$1 = "_inputWrap_1nw3y_243";
  const inputWithPostfix = "_inputWithPostfix_1nw3y_249";
  const inputPostfix = "_inputPostfix_1nw3y_253";
  const inputError$1 = "_inputError_1nw3y_266";
  const hintBlock = "_hintBlock_1nw3y_270";
  const hint$2 = "_hint_1nw3y_270";
  const payout = "_payout_1nw3y_278";
  const hintRow = "_hintRow_1nw3y_282";
  const error$4 = "_error_1nw3y_308";
  const linkButton = "_linkButton_1nw3y_315";
  const profileLink = "_profileLink_1nw3y_331";
  const notice = "_notice_1nw3y_342";
  const noticeWarning = "_noticeWarning_1nw3y_358";
  const noticeWarningLink = "_noticeWarningLink_1nw3y_369";
  const targetChecking = "_targetChecking_1nw3y_389";
  const targetAlert = "_targetAlert_1nw3y_397";
  const targetAlertHeading = "_targetAlertHeading_1nw3y_407";
  const targetAlertDetail = "_targetAlertDetail_1nw3y_415";
  const summaryList = "_summaryList_1nw3y_441";
  const summaryRow = "_summaryRow_1nw3y_450";
  const summaryTotal = "_summaryTotal_1nw3y_480";
  const summaryNegative = "_summaryNegative_1nw3y_489";
  const actions$4 = "_actions_1nw3y_494";
  const cancel = "_cancel_1nw3y_500";
  const confirm = "_confirm_1nw3y_501";
  const actionsSplit = "_actionsSplit_1nw3y_540";
  const actionCompact = "_actionCompact_1nw3y_548";
  const confirmCompact = "_confirmCompact_1nw3y_572";
  const gotItButton = "_gotItButton_1nw3y_587";
  const actionSecondary = "_actionSecondary_1nw3y_592";
  const pauseButton = "_pauseButton_1nw3y_604";
  const checkboxLabel = "_checkboxLabel_1nw3y_623";
  const checkbox = "_checkbox_1nw3y_623";
  const confirmDanger = "_confirmDanger_1nw3y_648";
  const confirmDangerFill = "_confirmDangerFill_1nw3y_661";
  const confirmDangerLabel = "_confirmDangerLabel_1nw3y_669";
  const holdHint = "_holdHint_1nw3y_674";
  const contractStyles = {
    overlay: overlay$1,
    overlayElevated,
    overlayElevatedTop,
    dialog: dialog$5,
    title: title$4,
    walletHeader,
    infoButton,
    infoPopover,
    introBanner,
    introText,
    introDismiss,
    tabs,
    tab,
    tabActive,
    trustNote,
    depositRedirect,
    summarySub,
    subtitle,
    label: label$2,
    input: input$3,
    inputWrap: inputWrap$1,
    inputWithPostfix,
    inputPostfix,
    inputError: inputError$1,
    hintBlock,
    hint: hint$2,
    payout,
    hintRow,
    error: error$4,
    linkButton,
    profileLink,
    notice,
    noticeWarning,
    noticeWarningLink,
    targetChecking,
    targetAlert,
    targetAlertHeading,
    targetAlertDetail,
    summaryList,
    summaryRow,
    summaryTotal,
    summaryNegative,
    actions: actions$4,
    cancel,
    confirm,
    actionsSplit,
    actionCompact,
    confirmCompact,
    gotItButton,
    actionSecondary,
    pauseButton,
    checkboxLabel,
    checkbox,
    confirmDanger,
    confirmDangerFill,
    confirmDangerLabel,
    holdHint
  };
  const button$2 = "_button_6731j_1";
  const scriptValue = "_scriptValue_6731j_38";
  const convertedValue = "_convertedValue_6731j_39";
  const conversion = "_conversion_6731j_63";
  const fromValue = "_fromValue_6731j_76";
  const arrow = "_arrow_6731j_83";
  const toValue = "_toValue_6731j_88";
  const formulaLine = "_formulaLine_6731j_95";
  const note$1 = "_note_6731j_103";
  const styles$s = {
    button: button$2,
    scriptValue,
    convertedValue,
    conversion,
    fromValue,
    arrow,
    toValue,
    formulaLine,
    note: note$1
  };
  function PayoutValue({
    amount,
    conversion: conversion2,
    label: label2 = "Payout",
    className
  }) {
    const [modalOpen, setModalOpen] = reactExports.useState(false);
    const price = conversion2.price;
    const canConvert = price !== null && Number.isFinite(amount) && Number.isFinite(price.averagePrice);
    const tornPayout = reactExports.useMemo(() => {
      if (!canConvert || !price) return null;
      return convertScriptDollarsToTornDollars(amount, price.averagePrice);
    }, [amount, canConvert, price]);
    if (!canConvert || tornPayout === null || !price) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "span",
        {
          className,
          title: conversion2.loading ? "Loading Torn Xanax market price..." : void 0,
          children: formatExtensionPoints(amount)
        }
      );
    }
    const extensionPayout = formatExtensionPoints(amount);
    const tornPayoutLabel = formatMoney(tornPayout);
    const averagePrice = formatMoney(price.averagePrice);
    const formula = formatPayoutFormula(amount, price.averagePrice);
    const modalTarget = getExtensionShadowMount();
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          className: `${styles$s.button} ${className ?? ""}`,
          title: `≈ ${tornPayoutLabel} in Torn dollars · click for details`,
          "aria-label": `${label2}: ${extensionPayout}, about ${tornPayoutLabel} in Torn dollars. Click for conversion details.`,
          onMouseDown: (e) => e.stopPropagation(),
          onKeyDown: (e) => e.stopPropagation(),
          onClick: (e) => {
            e.stopPropagation();
            setModalOpen(true);
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$s.scriptValue, children: extensionPayout }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$s.convertedValue, "aria-hidden": "true", children: tornPayoutLabel })
          ]
        }
      ),
      modalOpen && reactDomExports.createPortal(
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          PayoutConversionModal$1,
          {
            extensionPayout,
            averagePrice,
            tornPayout: tornPayoutLabel,
            formula,
            utcDate: price.utcDate,
            onClose: () => setModalOpen(false)
          }
        ),
        modalTarget ?? document.body
      )
    ] });
  }
  function PayoutConversionModal$1({
    extensionPayout,
    averagePrice,
    tornPayout,
    formula,
    utcDate,
    onClose
  }) {
    reactExports.useEffect(() => {
      const handleKeyDown = (e) => {
        if (e.key === "Escape") onClose();
      };
      window.addEventListener("keydown", handleKeyDown);
      return () => window.removeEventListener("keydown", handleKeyDown);
    }, [onClose]);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `${contractStyles.overlay} ${contractStyles.overlayElevated}`,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onClose),
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-payout-conversion-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-payout-conversion-title", className: contractStyles.title, children: "Torn payout estimate" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$s.conversion, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$s.fromValue, children: extensionPayout }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$s.arrow, "aria-hidden": "true", children: "→" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$s.toValue, children: tornPayout })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$s.formulaLine, children: formula }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: styles$s.note, children: [
                "Based on Torn's daily average Xanax price of ",
                averagePrice,
                " (",
                utcDate,
                "). A rough guide, not an exact trade value."
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: contractStyles.actions, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  className: contractStyles.confirm,
                  onClick: onClose,
                  children: "Close"
                }
              ) })
            ]
          }
        )
      }
    );
  }
  function parseQuantity(raw, max) {
    const trimmed = raw.trim();
    if (!/^\d+$/.test(trimmed)) return null;
    const value = Number(trimmed);
    if (value < CONTRACT_LOSS_MIN || value > max) return null;
    return value;
  }
  function ContractModal({
    listing,
    onConfirm,
    onCancel,
    payoutConversion,
    checkTargetStatus
  }) {
    const inputRef = reactExports.useRef(null);
    const confirmRef = reactExports.useRef(null);
    const [quantityInput, setQuantityInput] = reactExports.useState("1");
    const [error2, setError] = reactExports.useState(null);
    const [confirmSpotlight, setConfirmSpotlight] = reactExports.useState(false);
    const confirmSpotlightOpacity = useSpotlightFade(confirmSpotlight);
    const [firstContractDone, setFirstContractDone] = reactExports.useState(
      null
    );
    const firstContractCap = firstContractDone === false;
    const [targetChecking2, setTargetChecking] = reactExports.useState(false);
    const [targetStatus, setTargetStatus] = reactExports.useState(
      null
    );
    reactExports.useEffect(() => {
      if (!checkTargetStatus) return;
      let cancelled = false;
      setTargetStatus(null);
      setTargetChecking(true);
      void checkTargetStatus(listing.sellerId).then((status2) => {
        if (!cancelled) setTargetStatus(status2);
      }).catch(() => {
        if (!cancelled) setTargetStatus(null);
      }).finally(() => {
        if (!cancelled) setTargetChecking(false);
      });
      return () => {
        cancelled = true;
      };
    }, [checkTargetStatus, listing.sellerId]);
    const targetUnhittable = targetStatus != null && !targetStatus.hittable;
    reactExports.useEffect(() => {
      let cancelled = false;
      void hasFirstContractCompleted().then((completed) => {
        if (cancelled) return;
        setFirstContractDone(completed);
        if (!completed) setQuantityInput("1");
      });
      return () => {
        cancelled = true;
      };
    }, []);
    const effectiveMax = reactExports.useMemo(
      () => firstContractCap ? CONTRACT_LOSS_MIN : Math.max(
        CONTRACT_LOSS_MIN,
        Math.min(CONTRACT_LOSS_MAX, Math.floor(listing.quantity))
      ),
      [listing.quantity, firstContractCap]
    );
    const quantity2 = reactExports.useMemo(
      () => parseQuantity(quantityInput, effectiveMax),
      [quantityInput, effectiveMax]
    );
    const payout2 = quantity2 !== null ? listing.payPerLoss * quantity2 : null;
    reactExports.useEffect(() => {
      var _a2, _b;
      (_a2 = inputRef.current) == null ? void 0 : _a2.focus();
      (_b = inputRef.current) == null ? void 0 : _b.select();
    }, []);
    reactExports.useEffect(() => {
      return;
    }, []);
    const handleConfirm = reactExports.useCallback(() => {
      if (quantity2 === null) {
        setError(
          `Enter a whole number from ${CONTRACT_LOSS_MIN} to ${effectiveMax}.`
        );
        return;
      }
      onConfirm(quantity2, listing);
    }, [quantity2, effectiveMax, listing, onConfirm]);
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onCancel();
      } else if (e.key === "Enter") {
        e.preventDefault();
        handleConfirm();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        className: contractStyles.overlay,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onCancel),
        onKeyDown: handleKeyDown,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: contractStyles.dialog,
              role: "dialog",
              "aria-modal": "true",
              "aria-labelledby": "tlm-contract-title",
              onClick: (e) => e.stopPropagation(),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-contract-title", className: contractStyles.title, children: "Sell losses" }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: contractStyles.label, htmlFor: "tlm-contract-quantity", children: [
                  "How many losses would you like to sell to",
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "a",
                    {
                      className: contractStyles.profileLink,
                      href: getSellerProfileUrl(listing.sellerId),
                      target: "_blank",
                      rel: "noopener noreferrer",
                      onClick: (e) => e.stopPropagation(),
                      children: formatSellerId(listing.sellerId)
                    }
                  ),
                  "?"
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "input",
                  {
                    ref: inputRef,
                    id: "tlm-contract-quantity",
                    className: `${contractStyles.input} ${error2 ? contractStyles.inputError : ""}`,
                    type: "text",
                    inputMode: "numeric",
                    pattern: "[0-9]*",
                    autoComplete: "off",
                    value: quantityInput,
                    onKeyDown: (e) => {
                      if (e.key === "e" || e.key === "E" || e.key === "+" || e.key === "-" || e.key === "." || e.key === ",") {
                        e.preventDefault();
                      }
                    },
                    onChange: (e) => {
                      const digitsOnly = e.target.value.replace(/\D/g, "");
                      const capped = digitsOnly.length > 0 && Number(digitsOnly) > effectiveMax ? String(effectiveMax) : digitsOnly;
                      setQuantityInput(capped);
                      setError(null);
                    }
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.hintRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.hint, children: firstContractCap ? "Your first contract is limited to 1 loss." : `Enter a value between ${CONTRACT_LOSS_MIN} and ${effectiveMax}.` }),
                  payout2 !== null && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${contractStyles.payout} tlm-payout-hover-scope`, children: [
                    "Payout:",
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      PayoutValue,
                      {
                        amount: payout2,
                        conversion: payoutConversion,
                        label: "Contract payout"
                      }
                    )
                  ] })
                ] }),
                error2 && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.error, children: error2 }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: contractStyles.notice, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { style: { margin: 0 }, children: [
                  "You have ",
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("strong", { children: [
                    CONTRACT_FULFILL_MINUTES,
                    " minutes"
                  ] }),
                  " to fulfill this contract. Use a pillow to ensure a loss."
                ] }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: contractStyles.noticeWarning, children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { style: { margin: 0 }, children: "Payment is contingent on fulfilling the specified quantity." }) }),
                targetChecking2 && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.targetChecking, children: "Checking target's status…" }),
                targetUnhittable && targetStatus && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.targetAlert, role: "alert", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: contractStyles.targetAlertHeading, children: [
                    "⚠",
                    " ",
                    targetStatus.name ? targetStatus.name : `Target ${formatSellerId(listing.sellerId)}`,
                    " ",
                    "is ",
                    targetStatus.inHospital ? "in hospital" : "travelling",
                    " right now"
                  ] }),
                  targetStatus.description && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.targetAlertDetail, children: targetStatus.description }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.targetAlertDetail, children: "Are you sure you want to take this contract?" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.cancel, onClick: onCancel, children: "Cancel" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      ref: confirmRef,
                      type: "button",
                      className: contractStyles.confirm,
                      onClick: handleConfirm,
                      children: "Confirm"
                    }
                  )
                ] })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PanelButtonTutorial,
            {
              visible: confirmSpotlight,
              opacity: confirmSpotlightOpacity,
              fadeMs: 300,
              targetRef: confirmRef,
              onTransitionEnd: () => {
              },
              portalTarget: getExtensionShadowMount(),
              layerZIndex: API_KEY_SPOTLIGHT_Z,
              onDarknessClick: () => setConfirmSpotlight(false)
            }
          )
        ]
      }
    );
  }
  function externalLinkProps() {
    return isWebPlatform() ? { target: "_blank", rel: "noopener noreferrer" } : {};
  }
  function InsufficientBalanceMessage({
    onAddBalance
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: contractStyles.error, children: [
      "Insufficient balance for this order.",
      " ",
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          className: contractStyles.linkButton,
          onClick: onAddBalance,
          children: "Add to balance?"
        }
      )
    ] });
  }
  const TORN_ITEMS_URL = "https://www.torn.com/item.php";
  const TORN_ATTACK_PREFS_URL = "https://www.torn.com/preferences.php#tab=attack-preferences";
  function NoticeWarningLink({
    href,
    children
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx("a", { href, className: contractStyles.noticeWarningLink, ...externalLinkProps(), children });
  }
  function BuyerOrderConfirmModal({
    order,
    balance,
    error: error2,
    confirming = false,
    onConfirm,
    onCancel,
    onAddBalance,
    payoutConversion
  }) {
    const totalCost = order.payPerLoss * order.quantity;
    const remainingBalance = balance - totalCost;
    const insufficient = totalCost > balance;
    const contractLabel = CONTRACT_TYPE_LABELS[order.contractType].toLowerCase();
    const contractSingular = CONTRACT_TYPE_SINGULAR[order.contractType].toLowerCase();
    const sellBoardLabel = order.contractType === "losses" ? "Sell" : `Sell (${contractLabel})`;
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onCancel();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: contractStyles.overlay,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onCancel),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-buyer-confirm-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("h2", { id: "tlm-buyer-confirm-title", className: contractStyles.title, children: [
                "Confirm ",
                CONTRACT_TYPE_LABELS[order.contractType].toLowerCase(),
                " buy order"
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: contractStyles.subtitle, children: [
                "This will post your ",
                contractLabel,
                " contract to the ",
                sellBoardLabel,
                " ",
                "board and escrow the total cost from your balance."
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("dl", { className: contractStyles.summaryList, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${contractStyles.summaryRow} tlm-payout-hover-scope`, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: getPricePerLabel(order.contractType) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    PayoutValue,
                    {
                      amount: order.payPerLoss,
                      conversion: payoutConversion,
                      label: `Price per ${contractSingular}`
                    }
                  ) })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.summaryRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "Quantity" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { children: order.quantity.toLocaleString("en-US") })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "div",
                  {
                    className: `${contractStyles.summaryRow} ${contractStyles.summaryTotal} tlm-payout-hover-scope`,
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "Total cost" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                        PayoutValue,
                        {
                          amount: totalCost,
                          conversion: payoutConversion,
                          label: "Buy order total cost"
                        }
                      ) })
                    ]
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.summaryRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "Remaining balance" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { children: insufficient ? "—" : formatExtensionPoints(remainingBalance) })
                ] })
              ] }),
              error2 && !insufficient && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.error, children: error2 }),
              insufficient && /* @__PURE__ */ jsxRuntimeExports.jsx(InsufficientBalanceMessage, { onAddBalance }),
              order.contractType === "escapes" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: contractStyles.noticeWarning, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { style: { margin: 0 }, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(NoticeWarningLink, { href: TORN_ITEMS_URL, children: "Equip" }),
                " ",
                "pepper spray and enable temporary items to",
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx(NoticeWarningLink, { href: TORN_ATTACK_PREFS_URL, children: "auto equip" }),
                " ",
                "after fights. Ensure you have enough pepper spray."
              ] }) }),
              order.contractType === "stalemates" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: contractStyles.noticeWarning, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { style: { margin: 0 }, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(NoticeWarningLink, { href: TORN_ITEMS_URL, children: "Equip" }),
                " ",
                "and modify",
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx(NoticeWarningLink, { href: TORN_ATTACK_PREFS_URL, children: "attack settings" }),
                " ",
                "to only use a pillow."
              ] }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.cancel, onClick: onCancel, children: "Cancel" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.confirm,
                    onClick: onConfirm,
                    disabled: insufficient || confirming,
                    children: confirming ? "Checking…" : "Confirm"
                  }
                )
              ] })
            ]
          }
        )
      }
    );
  }
  async function invokeInsuranceFunction(functionName, accessToken, body2) {
    const platformFetch = getPlatformRuntime().fetch ?? fetch;
    const res = await platformFetch(
      `${SUPABASE_URL}/functions/v1/${functionName}`,
      {
        method: "POST",
        cache: "no-store",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${accessToken}`,
          apikey: SUPABASE_ANON_KEY
        },
        body: JSON.stringify(body2)
      }
    );
    const raw = await res.text();
    let data;
    try {
      data = JSON.parse(raw);
    } catch {
      throw new Error(
        `${functionName} failed (${res.status}): invalid response`
      );
    }
    if (!res.ok) {
      const message = data.error ?? `Request failed (${res.status})`;
      const err = new Error(message);
      err.status = res.status;
      if ("server_multiplier" in data) {
        err.server_multiplier = data.server_multiplier;
      }
      if ("server_payout" in data) {
        err.server_payout = data.server_payout;
      }
      throw err;
    }
    if (data.error) {
      throw new Error(data.error);
    }
    return data;
  }
  async function purchaseInsurancePolicy(accessToken, body2) {
    return invokeInsuranceFunction(
      "purchase_insurance_policy",
      accessToken,
      body2
    );
  }
  async function fileInsuranceClaim(accessToken, policyId, apiKey) {
    return invokeInsuranceFunction(
      "file_insurance_claim",
      accessToken,
      { policy_id: policyId, api_key: apiKey }
    );
  }
  async function setMyInsuranceAutoRenew(supabase2, policyId, autoRenew) {
    const { data, error: error2 } = await supabase2.rpc("set_my_insurance_auto_renew", {
      p_policy_id: policyId,
      p_auto_renew: autoRenew
    });
    if (error2) throw new Error(error2.message);
    return data;
  }
  function mapInsurancePolicyRow(row2) {
    return {
      id: row2.id,
      planId: row2.plan_id,
      coverage: Number(row2.premium),
      payout: Number(row2.payout),
      effectiveMultiplier: Number(row2.effective_multiplier),
      purchasedAt: new Date(row2.purchased_at).getTime(),
      endsAt: new Date(row2.ends_at).getTime(),
      autoRenew: row2.auto_renew,
      status: row2.status
    };
  }
  function formatCountdown(totalSeconds) {
    const clamped = Math.max(0, totalSeconds);
    const minutes = Math.floor(clamped / 60);
    const seconds = clamped % 60;
    return `${minutes}:${seconds.toString().padStart(2, "0")}`;
  }
  function formatInsuranceCountdown(totalSeconds) {
    const clamped = Math.max(0, totalSeconds);
    const hours = Math.floor(clamped / 3600);
    const minutes = Math.floor(clamped % 3600 / 60);
    const seconds = clamped % 60;
    if (hours > 0) {
      return `${hours}:${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`;
    }
    return formatCountdown(clamped);
  }
  const dialog$4 = "_dialog_7v3o5_1";
  const actions$3 = "_actions_7v3o5_5";
  const confirmFull = "_confirmFull_7v3o5_9";
  const autoRenewRow = "_autoRenewRow_7v3o5_15";
  const autoRenewText = "_autoRenewText_7v3o5_23";
  const switchInput = "_switchInput_7v3o5_38";
  const switchSlider = "_switchSlider_7v3o5_52";
  const styles$r = {
    dialog: dialog$4,
    actions: actions$3,
    confirmFull,
    autoRenewRow,
    autoRenewText,
    "switch": "_switch_7v3o5_31",
    switchInput,
    switchSlider
  };
  function InsuranceClaimModal({
    policy,
    accessToken,
    payoutConversion,
    onClose,
    onExpired,
    onClaimSuccess,
    onSetAutoRenew
  }) {
    const [submitting, setSubmitting] = reactExports.useState(false);
    const [closing, setClosing] = reactExports.useState(false);
    const [draftAutoRenew, setDraftAutoRenew] = reactExports.useState(policy.autoRenew);
    const [error2, setError] = reactExports.useState(null);
    const savedAutoRenewRef = reactExports.useRef(policy.autoRenew);
    reactExports.useEffect(() => {
      savedAutoRenewRef.current = policy.autoRenew;
      setDraftAutoRenew(policy.autoRenew);
    }, [policy.autoRenew, policy.id]);
    const handleExpired = reactExports.useCallback(() => {
      onExpired(policy.id);
      onClose();
    }, [onClose, onExpired, policy.id]);
    const secondsRemaining = useContractCountdown(policy.endsAt, handleExpired);
    const plan = getInsurancePlan(policy.planId);
    const planLabel = INSURANCE_PLAN_LABELS[policy.planId];
    const effectiveMultiplier = policy.effectiveMultiplier ?? plan.payoutMultiplier;
    const persistAutoRenewIfChanged = reactExports.useCallback(async () => {
      if (draftAutoRenew === savedAutoRenewRef.current) return;
      await onSetAutoRenew(policy.id, draftAutoRenew);
      savedAutoRenewRef.current = draftAutoRenew;
    }, [draftAutoRenew, onSetAutoRenew, policy.id]);
    const requestClose = reactExports.useCallback(async () => {
      if (closing || submitting) return;
      setClosing(true);
      setError(null);
      try {
        await persistAutoRenewIfChanged();
        onClose();
      } catch (e) {
        setError(
          e instanceof Error ? e.message : "Could not update auto-renew."
        );
      } finally {
        setClosing(false);
      }
    }, [closing, submitting, persistAutoRenewIfChanged, onClose]);
    const handleFileClaim = async () => {
      setError(null);
      setSubmitting(true);
      try {
        const apiKey = await getPlatformRuntime().auth.getApiKey();
        if (!apiKey) {
          setError(
            "API key not available — re-enter your Torn API key in Settings."
          );
          return;
        }
        const result = await fileInsuranceClaim(
          accessToken,
          policy.id,
          apiKey
        );
        onClaimSuccess(mapInsurancePolicyRow(result.policy));
        onClose();
      } catch (e) {
        setError(
          e instanceof Error ? e.message : "Unable to file claim right now."
        );
      } finally {
        setSubmitting(false);
      }
    };
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        void requestClose();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `${contractStyles.overlay} ${contractStyles.overlayElevated}`,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, () => void requestClose()),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: `${contractStyles.dialog} ${styles$r.dialog}`,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-insurance-claim-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-insurance-claim-title", className: contractStyles.title, children: "File insurance claim" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: contractStyles.subtitle, children: [
                planLabel,
                " · ",
                formatInsuranceDuration(plan.durationHours),
                " ·",
                " ",
                formatInsuranceMultiplier(effectiveMultiplier)
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("dl", { className: contractStyles.summaryList, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.summaryRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "Time left" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { children: formatInsuranceCountdown(secondsRemaining) })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "div",
                  {
                    className: `${contractStyles.summaryRow} ${contractStyles.summaryTotal} tlm-payout-hover-scope`,
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "Payout" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                        PayoutValue,
                        {
                          amount: policy.payout,
                          conversion: payoutConversion,
                          label: "Insurance payout"
                        }
                      ) })
                    ]
                  }
                )
              ] }),
              plan.supportsAutoRenew && /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: styles$r.autoRenewRow, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$r.switch, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "input",
                    {
                      type: "checkbox",
                      role: "switch",
                      className: styles$r.switchInput,
                      checked: draftAutoRenew,
                      disabled: submitting || closing,
                      onChange: (e) => setDraftAutoRenew(e.target.checked)
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$r.switchSlider, "aria-hidden": "true" })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$r.autoRenewText, children: "Auto-renew when this policy expires (charges payment if balance allows)" })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: contractStyles.noticeWarning, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { style: { margin: 0 }, children: [
                "Overdose must occur ",
                formatInsuranceInWindow(plan.durationHours),
                '. Click "File Claim" if you OD.'
              ] }) }),
              error2 && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.error, children: error2 }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: `${contractStyles.actions} ${styles$r.actions}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  className: `${contractStyles.confirm} ${styles$r.confirmFull}`,
                  onClick: () => void handleFileClaim(),
                  disabled: submitting || closing,
                  children: submitting ? "Filing claim…" : "File Claim"
                }
              ) })
            ]
          }
        )
      }
    );
  }
  const dialog$3 = "_dialog_199qm_1";
  const modalMain = "_modalMain_199qm_11";
  const selectionSlot = "_selectionSlot_199qm_18";
  const selectionSummary = "_selectionSummary_199qm_23";
  const selectionItem = "_selectionItem_199qm_35";
  const selectionLabel = "_selectionLabel_199qm_43";
  const selectionValue = "_selectionValue_199qm_51";
  const selectionValueWithLink = "_selectionValueWithLink_199qm_58";
  const selectionValuePlaceholder = "_selectionValuePlaceholder_199qm_62";
  const stepViewport = "_stepViewport_199qm_67";
  const stepPanel = "_stepPanel_199qm_74";
  const stepPanelForward = "_stepPanelForward_199qm_81";
  const stepPanelBack = "_stepPanelBack_199qm_86";
  const footer = "_footer_199qm_113";
  const stepper = "_stepper_199qm_118";
  const stepperSegment = "_stepperSegment_199qm_126";
  const step = "_step_199qm_67";
  const stepConnector = "_stepConnector_199qm_139";
  const stepConnectorTrack = "_stepConnectorTrack_199qm_149";
  const stepConnectorFill = "_stepConnectorFill_199qm_156";
  const stepConnectorFillComplete = "_stepConnectorFillComplete_199qm_166";
  const stepConnectorFillShoot = "_stepConnectorFillShoot_199qm_171";
  const stepDot = "_stepDot_199qm_189";
  const stepActive = "_stepActive_199qm_200";
  const stepComplete = "_stepComplete_199qm_206";
  const stepLabel = "_stepLabel_199qm_211";
  const stepperRed = "_stepperRed_199qm_226";
  const stepperGray = "_stepperGray_199qm_237";
  const block$2 = "_block_199qm_248";
  const blockTitle = "_blockTitle_199qm_258";
  const planList = "_planList_199qm_267";
  const planCard = "_planCard_199qm_276";
  const planCardSelected = "_planCardSelected_199qm_301";
  const planCardBlocked = "_planCardBlocked_199qm_307";
  const planCardHeader = "_planCardHeader_199qm_312";
  const planCardTitle = "_planCardTitle_199qm_319";
  const planCardBadges = "_planCardBadges_199qm_325";
  const planBadge = "_planBadge_199qm_332";
  const planBadgeMultiplier = "_planBadgeMultiplier_199qm_343";
  const planCardSubtitle = "_planCardSubtitle_199qm_348";
  const field$2 = "_field_199qm_355";
  const fieldLabel$1 = "_fieldLabel_199qm_361";
  const coverageSegments = "_coverageSegments_199qm_369";
  const coverageSegmentPill = "_coverageSegmentPill_199qm_382";
  const coverageSegment = "_coverageSegment_199qm_369";
  const coveragePayoutBar = "_coveragePayoutBar_199qm_429";
  const coveragePayoutBarLabel = "_coveragePayoutBarLabel_199qm_442";
  const coveragePayoutBarValue = "_coveragePayoutBarValue_199qm_449";
  const coveragePayoutBarValuePlaceholder = "_coveragePayoutBarValuePlaceholder_199qm_458";
  const reviewHint$1 = "_reviewHint_199qm_534";
  const autoRenewLabel = "_autoRenewLabel_199qm_542";
  const autoRenewCheckbox = "_autoRenewCheckbox_199qm_553";
  const confirmCostGroup = "_confirmCostGroup_199qm_834";
  const confirmCostRow = "_confirmCostRow_199qm_842";
  const confirmBalanceLabel = "_confirmBalanceLabel_199qm_868";
  const confirmBalanceValue = "_confirmBalanceValue_199qm_876";
  const error$3 = "_error_199qm_893";
  const hint$1 = "_hint_199qm_899";
  const errorSlot = "_errorSlot_199qm_906";
  const summaryStyles = {
    dialog: dialog$3,
    modalMain,
    selectionSlot,
    selectionSummary,
    selectionItem,
    selectionLabel,
    selectionValue,
    selectionValueWithLink,
    selectionValuePlaceholder,
    stepViewport,
    stepPanel,
    stepPanelForward,
    stepPanelBack,
    footer,
    stepper,
    stepperSegment,
    step,
    stepConnector,
    stepConnectorTrack,
    stepConnectorFill,
    stepConnectorFillComplete,
    stepConnectorFillShoot,
    stepDot,
    stepActive,
    stepComplete,
    stepLabel,
    stepperRed,
    stepperGray,
    block: block$2,
    blockTitle,
    planList,
    planCard,
    planCardSelected,
    planCardBlocked,
    planCardHeader,
    planCardTitle,
    planCardBadges,
    planBadge,
    planBadgeMultiplier,
    planCardSubtitle,
    field: field$2,
    fieldLabel: fieldLabel$1,
    coverageSegments,
    coverageSegmentPill,
    coverageSegment,
    coveragePayoutBar,
    coveragePayoutBarLabel,
    coveragePayoutBarValue,
    coveragePayoutBarValuePlaceholder,
    reviewHint: reviewHint$1,
    autoRenewLabel,
    autoRenewCheckbox,
    confirmCostGroup,
    confirmCostRow,
    confirmBalanceLabel,
    confirmBalanceValue,
    error: error$3,
    hint: hint$1,
    errorSlot
  };
  const PLACEHOLDER$5 = "—";
  function SummaryValue$5({
    value,
    formatted
  }) {
    const display = formatted ?? value;
    if (!display) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "span",
        {
          className: `${summaryStyles.selectionValue} ${summaryStyles.selectionValuePlaceholder}`,
          children: PLACEHOLDER$5
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionValue, children: display });
  }
  function InsurancePolicySummary({
    plan,
    effectiveMultiplier,
    premium,
    payout: payout2,
    autoRenew,
    showAutoRenew = false,
    "aria-label": ariaLabel = "Policy summary"
  }) {
    const multiplier = effectiveMultiplier ?? (plan == null ? void 0 : plan.payoutMultiplier) ?? null;
    const planDisplay = plan && multiplier !== null ? `${plan.label} · ${formatInsuranceDuration(plan.durationHours)} · ${formatInsuranceMultiplier(multiplier)}` : null;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("ul", { className: summaryStyles.selectionSummary, "aria-label": ariaLabel, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Plan" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryValue$5, { value: planDisplay })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Your payment" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          SummaryValue$5,
          {
            value: null,
            formatted: premium !== null ? formatExtensionPoints(premium) : null
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Payout" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          SummaryValue$5,
          {
            value: null,
            formatted: payout2 !== null ? formatExtensionPoints(payout2) : null
          }
        )
      ] }),
      showAutoRenew && /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Auto-renew" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryValue$5, { value: autoRenew ? "On" : "Off" })
      ] })
    ] });
  }
  function InsuranceConfirmModal({
    purchase,
    balance,
    error: error2,
    confirming,
    onConfirm,
    onBack,
    onAddBalance
  }) {
    const plan = getInsurancePlan(purchase.planId);
    const insufficient = purchase.coverage > balance;
    const remainingBalance = balance - purchase.coverage;
    const showRenewNotice = !(plan.supportsAutoRenew && purchase.autoRenew);
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onBack();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `${contractStyles.overlay} ${contractStyles.overlayElevated} ${contractStyles.overlayElevatedTop}`,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onBack),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-insurance-confirm-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-insurance-confirm-title", className: contractStyles.title, children: "Confirm insurance purchase" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                InsurancePolicySummary,
                {
                  plan,
                  effectiveMultiplier: purchase.effectiveMultiplier,
                  premium: purchase.coverage,
                  payout: purchase.payout,
                  autoRenew: purchase.autoRenew,
                  showAutoRenew: plan.supportsAutoRenew && purchase.autoRenew
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: contractStyles.noticeWarning, children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { style: { margin: 0 }, children: "You must file the insurance claim after you OD." }) }),
              showRenewNotice && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: contractStyles.noticeWarning, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { style: { margin: 0 }, children: [
                "Overdose must occur",
                " ",
                formatInsuranceWithinWindow(plan.durationHours),
                "."
              ] }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostGroup, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceLabel, children: "Total cost" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceValue, children: formatExtensionPoints(purchase.coverage) })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceLabel, children: "Remaining balance" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceValue, children: insufficient ? "—" : formatExtensionPoints(remainingBalance) })
                ] })
              ] }),
              error2 && !insufficient && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.error, children: error2 }),
              insufficient && /* @__PURE__ */ jsxRuntimeExports.jsx(InsufficientBalanceMessage, { onAddBalance }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.cancel, onClick: onBack, children: "Back" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.confirm,
                    onClick: onConfirm,
                    disabled: insufficient || confirming,
                    children: confirming ? "Purchasing…" : "Confirm purchase"
                  }
                )
              ] })
            ]
          }
        )
      }
    );
  }
  const AUTO_RENEW_KEY_PREFIX = "insurance_auto_renew_";
  function autoRenewKey(tornXid) {
    return tornXid == null ? `${AUTO_RENEW_KEY_PREFIX}guest` : `${AUTO_RENEW_KEY_PREFIX}${tornXid}`;
  }
  function readStoredInsuranceAutoRenewSync(tornXid) {
    try {
      return readLocalStorageWithMigration(localStorage, autoRenewKey(tornXid)) === "1";
    } catch {
      return false;
    }
  }
  async function loadInsuranceAutoRenew(tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        autoRenewKey(tornXid)
      );
      if (raw === true || raw === "1") return true;
      if (raw === false || raw === "0") return false;
    } catch {
    }
    return readStoredInsuranceAutoRenewSync(tornXid);
  }
  async function saveInsuranceAutoRenew(tornXid, enabled) {
    try {
      writeLocalStorageCurrent(
        localStorage,
        autoRenewKey(tornXid),
        enabled ? "1" : "0"
      );
    } catch {
    }
    try {
      await getPlatformRuntime().storage.set(autoRenewKey(tornXid), enabled);
    } catch {
    }
  }
  const wrapper = "_wrapper_8lgpn_1";
  const group$1 = "_group_8lgpn_7";
  const tooltip$2 = "_tooltip_8lgpn_22";
  const tooltipLine = "_tooltipLine_8lgpn_40";
  const groupError = "_groupError_8lgpn_55";
  const symbol = "_symbol_8lgpn_59";
  const input$2 = "_input_8lgpn_96";
  const postfix = "_postfix_8lgpn_117";
  const styles$q = {
    wrapper,
    group: group$1,
    tooltip: tooltip$2,
    tooltipLine,
    groupError,
    symbol,
    input: input$2,
    postfix
  };
  const TOOLTIP_LINES = [
    "Click here to add the maximum amount, or use shortcuts like",
    "5k, 1.5m, max, half, quarter, 1/2, 1/3, 1/4, 25%"
  ];
  const TOOLTIP_LABEL = TOOLTIP_LINES.join(" ");
  const hasShortcutChars = (raw) => /[a-z%/]/i.test(raw);
  function PtsAmountInput({
    value,
    onChange,
    max,
    referenceMax,
    sanitize: sanitize2,
    symbolLabel = "PTS",
    inputMode = "numeric",
    id: id2,
    placeholder,
    className,
    inputClassName,
    ariaLabel,
    hasError = false,
    disabled = false,
    inputRef,
    onEnter,
    postfix: postfix2,
    symbolDisabled = false
  }) {
    const [tooltipOpen, setTooltipOpen] = reactExports.useState(false);
    const internalRef = reactExports.useRef(null);
    const assignRef = (node) => {
      internalRef.current = node;
      if (inputRef) {
        inputRef.current = node;
      }
    };
    const reference = referenceMax !== void 0 && Number.isFinite(referenceMax) ? referenceMax : max;
    const sanitizeRaw = (raw) => sanitize2 ? sanitize2(raw) : sanitizeAmountInput(raw, max);
    const formatNumber = (n) => Math.min(Math.max(0, Math.round(n)), max).toLocaleString("en-US");
    const handleChange = (raw) => {
      if (isCompleteShortcut(raw)) {
        const resolved = resolveAmountShortcut(raw, reference);
        onChange(resolved === null ? sanitizeRaw(raw) : formatNumber(resolved));
        return;
      }
      if (isShortcutInProgress(raw)) {
        onChange(raw);
        return;
      }
      onChange(sanitizeRaw(raw));
    };
    const resolveValue = () => {
      if (!hasShortcutChars(value)) return value;
      const resolved = resolveAmountShortcut(value, reference);
      return resolved === null ? sanitizeRaw(value) : formatNumber(resolved);
    };
    const commitShortcut = () => {
      const next = resolveValue();
      if (next !== value) onChange(next);
      return next;
    };
    const fillMax = () => {
      var _a2;
      if (disabled || symbolDisabled) return;
      onChange(formatNumber(reference));
      (_a2 = internalRef.current) == null ? void 0 : _a2.focus();
    };
    const showTooltip = tooltipOpen && !disabled && !symbolDisabled;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$q.wrapper} ${className ?? ""}`, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$q.group} ${hasError ? styles$q.groupError : ""}`, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "button",
            className: styles$q.symbol,
            onClick: fillMax,
            onMouseEnter: () => setTooltipOpen(true),
            onMouseLeave: () => setTooltipOpen(false),
            onFocus: () => setTooltipOpen(true),
            onBlur: () => setTooltipOpen(false),
            disabled: disabled || symbolDisabled,
            "aria-label": `${TOOLTIP_LABEL} (${symbolLabel})`,
            tabIndex: -1,
            children: symbolLabel
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "input",
          {
            ref: assignRef,
            id: id2,
            className: `${styles$q.input} ${inputClassName ?? ""}`,
            type: "text",
            inputMode,
            placeholder,
            value,
            disabled,
            "aria-label": ariaLabel,
            autoComplete: "off",
            autoCorrect: "off",
            autoCapitalize: "off",
            spellCheck: false,
            onChange: (e) => handleChange(e.target.value),
            onBlur: () => commitShortcut(),
            onKeyDown: (e) => {
              if (e.key === "Enter") {
                const committed = commitShortcut();
                onEnter == null ? void 0 : onEnter(committed);
              }
            }
          }
        ),
        postfix2 != null && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$q.postfix, "aria-hidden": "true", children: postfix2 })
      ] }),
      showTooltip && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$q.tooltip, role: "tooltip", children: TOOLTIP_LINES.map((line, i) => /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$q.tooltipLine, children: line }, i)) })
    ] });
  }
  function getCoverageValidationMessage(raw) {
    const trimmed = raw.trim();
    if (!trimmed) return null;
    const value = evaluateNumericInput(trimmed);
    if (value === null) {
      return `Enter a valid amount (${formatExtensionPoints(INSURANCE_COVERAGE_MIN)}–${formatExtensionPoints(INSURANCE_COVERAGE_MAX)}, optional k/m/b).`;
    }
    if (!Number.isInteger(value)) {
      return "Coverage must be a whole number (e.g. 100k or 2m).";
    }
    if (value < INSURANCE_COVERAGE_MIN) {
      return `Coverage must be at least ${formatExtensionPoints(INSURANCE_COVERAGE_MIN)}.`;
    }
    if (value > INSURANCE_COVERAGE_MAX) {
      return `Coverage cannot exceed ${formatExtensionPoints(INSURANCE_COVERAGE_MAX)}.`;
    }
    return null;
  }
  const PAYMENT_RANGE_LABEL = `Your payment (${INSURANCE_COVERAGE_MIN.toLocaleString("en-US")} – ${INSURANCE_COVERAGE_MAX.toLocaleString("en-US")} PTS)`;
  const COVERAGE_PRESET_OPTIONS = [
    { id: "100k", label: "100k" },
    { id: "1m", label: "1M" },
    { id: "10m", label: "10M" },
    { id: "custom", label: "Custom" }
  ];
  function formatCoveragePresetInput(preset) {
    if (preset === "100k") return "100k";
    if (preset === "1m") return "1m";
    return "10m";
  }
  const STEPS$5 = [
    { id: "plan", label: "Plan" },
    { id: "coverage", label: "Coverage" },
    { id: "options", label: "Options" },
    { id: "review", label: "Review" }
  ];
  function stepIndex$5(step2, includeOptions) {
    const order = includeOptions ? ["plan", "coverage", "options", "review"] : ["plan", "coverage", "review"];
    return order.indexOf(step2);
  }
  function getVisibleSteps(includeOptions) {
    return STEPS$5.filter((s) => s.id !== "options" || includeOptions);
  }
  function InsurancePolicyModal({
    open,
    activePolicies,
    availableBalance,
    tornXid,
    effectiveMultipliers,
    perksLoading,
    perksError,
    onPurchase,
    onClose,
    onAddBalance
  }) {
    const [step2, setStep] = reactExports.useState("plan");
    const [selectedPlanId, setSelectedPlanId] = reactExports.useState(
      null
    );
    const [coverageInput, setCoverageInput] = reactExports.useState("");
    const [coveragePreset, setCoveragePreset] = reactExports.useState(
      null
    );
    const customCoverageInputRef = reactExports.useRef(null);
    const [autoRenew, setAutoRenew] = reactExports.useState(false);
    const [error2, setError] = reactExports.useState(null);
    const [slideDirection, setSlideDirection] = reactExports.useState(
      "forward"
    );
    const [connectorShootIndex, setConnectorShootIndex] = reactExports.useState(
      null
    );
    const selectedPlan = selectedPlanId ? getInsurancePlan(selectedPlanId) : null;
    const includeOptionsStep = (selectedPlan == null ? void 0 : selectedPlan.supportsAutoRenew) ?? false;
    const visibleSteps = getVisibleSteps(includeOptionsStep);
    const planBlocked = selectedPlanId != null && activePolicies.some(
      (p) => p.planId === selectedPlanId && p.status === "active"
    );
    const selectedEffectiveMultiplier = selectedPlanId && effectiveMultipliers ? effectiveMultipliers[selectedPlanId] : null;
    reactExports.useEffect(() => {
      if (!open) return;
      let cancelled = false;
      void loadInsuranceAutoRenew(tornXid).then((stored) => {
        if (!cancelled) setAutoRenew(stored);
      });
      return () => {
        cancelled = true;
      };
    }, [open, tornXid]);
    reactExports.useEffect(() => {
      if (!open) {
        setStep("plan");
        setSelectedPlanId(null);
        setCoverageInput("");
        setCoveragePreset(null);
        setError(null);
        setSlideDirection("forward");
        setConnectorShootIndex(null);
      }
    }, [open]);
    reactExports.useEffect(() => {
      if (!(selectedPlan == null ? void 0 : selectedPlan.supportsAutoRenew)) {
        setAutoRenew(false);
      }
    }, [selectedPlanId, selectedPlan == null ? void 0 : selectedPlan.supportsAutoRenew]);
    reactExports.useEffect(() => {
      var _a2;
      if (coveragePreset !== "custom") return;
      (_a2 = customCoverageInputRef.current) == null ? void 0 : _a2.focus();
    }, [coveragePreset]);
    reactExports.useEffect(() => {
      if (step2 !== "coverage" || coveragePreset !== null) return;
      setCoveragePreset("100k");
      setCoverageInput("100k");
    }, [step2, coveragePreset]);
    const coveragePresetIndex = coveragePreset === null ? -1 : COVERAGE_PRESET_OPTIONS.findIndex((option) => option.id === coveragePreset);
    const coverage = reactExports.useMemo(
      () => parseInsurancePremiumInput(coverageInput),
      [coverageInput]
    );
    const coverageValidation = reactExports.useMemo(
      () => getCoverageValidationMessage(coverageInput),
      [coverageInput]
    );
    const hasValidCoverage = coverage !== null && coverageValidation === null && !planBlocked;
    const summaryPayout = hasValidCoverage && selectedPlanId && selectedEffectiveMultiplier !== null ? computeInsurancePayout(coverage, selectedEffectiveMultiplier) : null;
    const summaryPremium = hasValidCoverage ? coverage : null;
    const activeStepIndex = stepIndex$5(step2, includeOptionsStep);
    const showBack = step2 !== "plan";
    const perksReady = !perksLoading && effectiveMultipliers !== null && !perksError;
    const canAdvanceCoverage = hasValidCoverage && coverage !== null;
    const canPurchase = perksReady && hasValidCoverage && coverage !== null && selectedEffectiveMultiplier !== null && coverage <= availableBalance && step2 === "review";
    const goToStep = (next, direction) => {
      const prevIndex = stepIndex$5(step2, includeOptionsStep);
      const nextIndex = stepIndex$5(next, includeOptionsStep);
      if (direction === "forward" && nextIndex > prevIndex) {
        setConnectorShootIndex(prevIndex);
        globalThis.setTimeout(() => setConnectorShootIndex(null), 520);
      }
      setSlideDirection(direction);
      setStep(next);
    };
    const handleAutoRenewChange = (checked) => {
      setAutoRenew(checked);
      void saveInsuranceAutoRenew(tornXid, checked);
    };
    const handleSelectCoveragePreset = (preset) => {
      setCoveragePreset(preset);
      setError(null);
      if (preset === "custom") {
        setCoverageInput("");
        return;
      }
      setCoverageInput(formatCoveragePresetInput(preset));
    };
    const handleSelectPlan = (planId) => {
      if (activePolicies.some((p) => p.planId === planId && p.status === "active")) {
        return;
      }
      if (!perksReady || !effectiveMultipliers) return;
      setSelectedPlanId(planId);
      setCoveragePreset("100k");
      setCoverageInput("100k");
      setError(null);
      goToStep("coverage", "forward");
    };
    const handleBack = () => {
      setError(null);
      if (step2 === "coverage") goToStep("plan", "back");
      else if (step2 === "options") goToStep("coverage", "back");
      else if (step2 === "review") {
        goToStep(includeOptionsStep ? "options" : "coverage", "back");
      }
    };
    const handlePrimary = () => {
      if (step2 === "coverage") {
        if (!canAdvanceCoverage) {
          if (coverage === null || coverageValidation) {
            setError(
              `Enter valid coverage (${formatExtensionPoints(INSURANCE_COVERAGE_MIN)}–${formatExtensionPoints(INSURANCE_COVERAGE_MAX)}).`
            );
          }
          return;
        }
        if (coverage > availableBalance) {
          setError("insufficient_balance");
          return;
        }
        setError(null);
        goToStep(includeOptionsStep ? "options" : "review", "forward");
        return;
      }
      if (step2 === "options") {
        goToStep("review", "forward");
        return;
      }
      if (step2 === "review") {
        handlePurchase();
      }
    };
    const handlePurchase = () => {
      if (!selectedPlanId || planBlocked || !selectedPlan || coverage === null || selectedEffectiveMultiplier === null) {
        return;
      }
      if (coverage > availableBalance) {
        setError("insufficient_balance");
        return;
      }
      setError(null);
      onPurchase({
        planId: selectedPlanId,
        coverage,
        payout: computeInsurancePayout(coverage, selectedEffectiveMultiplier),
        effectiveMultiplier: selectedEffectiveMultiplier,
        autoRenew: selectedPlan.supportsAutoRenew && autoRenew
      });
    };
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        if (showBack) handleBack();
        else onClose();
      }
    };
    const primaryLabel = step2 === "review" ? "Review" : "Continue";
    const primaryDisabled = step2 === "coverage" ? !canAdvanceCoverage : step2 === "review" ? !canPurchase : false;
    const showPrimary = step2 !== "plan";
    const renderStepContent = () => {
      if (step2 === "plan") {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.block, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: summaryStyles.blockTitle, children: "Select a plan" }),
          perksLoading && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: summaryStyles.hint, children: "Loading your payout multipliers…" }),
          perksError && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: summaryStyles.error, children: perksError }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { role: "radiogroup", "aria-label": "Insurance plan", children: /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: summaryStyles.planList, children: INSURANCE_PLANS.map((plan) => {
            const selected = plan.id === selectedPlanId;
            const hasActive = activePolicies.some(
              (p) => p.planId === plan.id && p.status === "active"
            );
            const effectiveMult = effectiveMultipliers == null ? void 0 : effectiveMultipliers[plan.id];
            const multLabel = effectiveMult !== void 0 ? formatInsuranceMultiplier(effectiveMult) : perksLoading ? "…" : formatInsuranceMultiplier(plan.payoutMultiplier);
            return /* @__PURE__ */ jsxRuntimeExports.jsx("li", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "button",
              {
                type: "button",
                role: "radio",
                "aria-checked": selected,
                className: `${summaryStyles.planCard} ${selected ? summaryStyles.planCardSelected : ""} ${hasActive ? summaryStyles.planCardBlocked : ""}`,
                disabled: hasActive || !perksReady,
                onClick: () => handleSelectPlan(plan.id),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.planCardHeader, children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: summaryStyles.planCardTitle, children: [
                      plan.label,
                      hasActive ? " — active" : ""
                    ] }),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: summaryStyles.planCardBadges, children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.planBadge, children: formatInsuranceDuration(plan.durationHours) }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "span",
                        {
                          className: `${summaryStyles.planBadge} ${summaryStyles.planBadgeMultiplier}`,
                          children: multLabel
                        }
                      )
                    ] })
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: summaryStyles.planCardSubtitle, children: plan.subtitle })
                ]
              }
            ) }, plan.id);
          }) }) }),
          planBlocked && selectedPlan && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: summaryStyles.error, children: [
            "Active ",
            selectedPlan.label,
            " policy — file a claim or wait for it to expire before buying again."
          ] })
        ] });
      }
      if (step2 === "coverage" && selectedPlan) {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.block, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.field, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.fieldLabel, children: PAYMENT_RANGE_LABEL }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "div",
              {
                className: summaryStyles.coverageSegments,
                role: "radiogroup",
                "aria-label": "Payment amount",
                children: [
                  coveragePresetIndex >= 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "div",
                    {
                      className: summaryStyles.coverageSegmentPill,
                      style: {
                        transform: `translateX(${coveragePresetIndex * 100}%)`
                      },
                      "aria-hidden": "true"
                    }
                  ),
                  COVERAGE_PRESET_OPTIONS.map((option) => {
                    const selected = coveragePreset === option.id;
                    return /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        role: "radio",
                        "aria-checked": selected,
                        className: summaryStyles.coverageSegment,
                        onClick: () => handleSelectCoveragePreset(option.id),
                        children: option.label
                      },
                      option.id
                    );
                  })
                ]
              }
            ),
            coveragePreset === "custom" && /* @__PURE__ */ jsxRuntimeExports.jsx(
              PtsAmountInput,
              {
                id: "tlm-insurance-modal-coverage",
                inputRef: customCoverageInputRef,
                value: coverageInput,
                onChange: (next) => {
                  setCoveragePreset("custom");
                  setCoverageInput(next);
                  setError(null);
                },
                max: INSURANCE_COVERAGE_MAX,
                referenceMax: availableBalance,
                sanitize: sanitizeInsurancePremiumInput,
                inputMode: "decimal",
                placeholder: "e.g. 500k, 2m",
                hasError: Boolean(error2 && coverage === null && coverageInput)
              }
            )
          ] }),
          coverageValidation && coverageInput.trim() && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: summaryStyles.error, children: coverageValidation })
        ] });
      }
      if (step2 === "options" && selectedPlan) {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.block, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: summaryStyles.blockTitle, children: "Policy options" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: summaryStyles.autoRenewLabel, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "input",
              {
                type: "checkbox",
                className: summaryStyles.autoRenewCheckbox,
                checked: autoRenew,
                onChange: (e) => handleAutoRenewChange(e.target.checked)
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Auto-renew when this policy expires (charges payment if balance allows)" })
          ] })
        ] });
      }
      if (step2 === "review" && selectedPlan && coverage !== null) {
        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.block, children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: summaryStyles.reviewHint, children: "Everything looks good. Continue to review and pay." }) });
      }
      return null;
    };
    if (!open) return null;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `${contractStyles.overlay} ${contractStyles.overlayElevated}`,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onClose),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: `${contractStyles.dialog} ${summaryStyles.dialog}`,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-insurance-policy-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-insurance-policy-title", className: contractStyles.title, children: "Create OD insurance policy" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.modalMain, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("ol", { className: summaryStyles.stepper, "aria-label": "Policy setup progress", children: visibleSteps.map((s, index) => {
                  const idx = stepIndex$5(s.id, includeOptionsStep);
                  const complete = idx < activeStepIndex;
                  const active = idx === activeStepIndex;
                  const isLast = index === visibleSteps.length - 1;
                  return /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.stepperSegment, children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      "div",
                      {
                        className: `${summaryStyles.step} ${complete ? summaryStyles.stepComplete : ""} ${active ? summaryStyles.stepActive : ""}`,
                        children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepDot, "aria-hidden": "true" }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepLabel, children: s.label })
                        ]
                      }
                    ),
                    !isLast && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.stepConnector, "aria-hidden": "true", children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepConnectorTrack }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "span",
                        {
                          className: `${summaryStyles.stepConnectorFill} ${idx < activeStepIndex ? summaryStyles.stepConnectorFillComplete : ""} ${connectorShootIndex === idx ? summaryStyles.stepConnectorFillShoot : ""}`
                        }
                      )
                    ] })
                  ] }, s.id);
                }) }),
                step2 !== "plan" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.selectionSlot, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  InsurancePolicySummary,
                  {
                    plan: selectedPlan,
                    effectiveMultiplier: selectedEffectiveMultiplier,
                    premium: summaryPremium,
                    payout: summaryPayout,
                    autoRenew,
                    showAutoRenew: includeOptionsStep && (step2 === "options" || step2 === "review")
                  }
                ) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.stepViewport, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "div",
                  {
                    className: `${summaryStyles.stepPanel} ${slideDirection === "forward" ? summaryStyles.stepPanelForward : summaryStyles.stepPanelBack}`,
                    children: renderStepContent()
                  },
                  step2
                ) }),
                (error2 === "insufficient_balance" || error2 && error2 !== "insufficient_balance") && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.errorSlot, children: error2 === "insufficient_balance" ? /* @__PURE__ */ jsxRuntimeExports.jsx(InsufficientBalanceMessage, { onAddBalance }) : /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: summaryStyles.error, children: error2 }) }),
                step2 === "coverage" && /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "div",
                  {
                    className: summaryStyles.coveragePayoutBar,
                    "aria-live": "polite",
                    "aria-atomic": "true",
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.coveragePayoutBarLabel, children: "Payout if you OD" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "span",
                        {
                          className: `${summaryStyles.coveragePayoutBarValue} ${summaryPayout === null ? summaryStyles.coveragePayoutBarValuePlaceholder : ""}`,
                          children: summaryPayout !== null ? formatExtensionPoints(summaryPayout) : "—"
                        }
                      )
                    ]
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${contractStyles.actions} ${summaryStyles.footer}`, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.cancel,
                    onClick: showBack ? handleBack : onClose,
                    children: showBack ? "Back" : "Cancel"
                  }
                ),
                showPrimary && /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.confirm,
                    onClick: handlePrimary,
                    disabled: primaryDisabled,
                    children: primaryLabel
                  }
                )
              ] })
            ]
          }
        )
      }
    );
  }
  function getTornProfileUrl(targetId) {
    return `https://www.torn.com/profiles.php?XID=${targetId}`;
  }
  function getTornBountyAddUrl(targetId) {
    return `https://www.torn.com/bounties.php?p=add&XID=${targetId}`;
  }
  const card$3 = "_card_1wr24_1";
  const badge$4 = "_badge_1wr24_11";
  const targetLink = "_targetLink_1wr24_16";
  const targetSep = "_targetSep_1wr24_27";
  const payoutValue$2 = "_payoutValue_1wr24_31";
  const styles$p = {
    card: card$3,
    badge: badge$4,
    targetLink,
    targetSep,
    payoutValue: payoutValue$2
  };
  function BountyTargetLinks({
    targetIds,
    className,
    linkClassName = styles$p.targetLink
  }) {
    if (targetIds.length === 0) return /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: "—" });
    const prefix = targetIds.length > 1 ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      targetIds.length,
      " players ·",
      " "
    ] }) : null;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className, children: [
      prefix,
      targetIds.map((id2, index) => /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
        index > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$p.targetSep, children: ", " }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "a",
          {
            className: linkClassName,
            href: getTornProfileUrl(id2),
            target: "_blank",
            rel: "noopener noreferrer",
            onClick: (e) => e.stopPropagation(),
            children: String(id2)
          }
        )
      ] }, id2))
    ] });
  }
  const PLACEHOLDER$4 = "—";
  function SummaryValue$4({
    children
  }) {
    if (children == null || children === false || typeof children === "string" && !children) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "span",
        {
          className: `${summaryStyles.selectionValue} ${summaryStyles.selectionValuePlaceholder}`,
          children: PLACEHOLDER$4
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionValue, children });
  }
  function BountyOrderSummary({
    targetIds,
    bountyValueTorn,
    quantity: quantity2
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("ul", { className: summaryStyles.selectionSummary, "aria-label": "Bounty order summary", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Target(s)" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryValue$4, { children: targetIds != null && targetIds.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(BountyTargetLinks, { targetIds }) : null })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Bounty value" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryValue$4, { children: bountyValueTorn != null ? `${formatMoney(bountyValueTorn)} each` : null })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Quantity" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryValue$4, { children: quantity2 != null ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          quantity2.toLocaleString("en-US"),
          targetIds != null && targetIds.length > 1 ? " per target" : ""
        ] }) : null })
      ] })
    ] });
  }
  const primaryDisplay = "_primaryDisplay_17aop_1";
  const altDisplay = "_altDisplay_17aop_2";
  const button$1 = "_button_17aop_16";
  const tornStyles = {
    primaryDisplay,
    altDisplay,
    button: button$1
  };
  function TornPrimaryValue({
    tornAmount,
    ptsAmount,
    conversion: conversion2,
    label: label2 = "Amount",
    className
  }) {
    const [modalOpen, setModalOpen] = reactExports.useState(false);
    const price = conversion2.price;
    const resolved = reactExports.useMemo(() => {
      if (tornAmount != null && Number.isFinite(tornAmount)) {
        const pts = price != null && Number.isFinite(price.averagePrice) ? convertTornDollarsToScriptPoints(tornAmount, price.averagePrice) : null;
        return { torn: tornAmount, pts };
      }
      if (ptsAmount != null && Number.isFinite(ptsAmount)) {
        const torn = price != null && Number.isFinite(price.averagePrice) ? convertScriptDollarsToTornDollars(ptsAmount, price.averagePrice) : null;
        return { torn, pts: ptsAmount };
      }
      return { torn: null, pts: null };
    }, [tornAmount, ptsAmount, price]);
    if (resolved.torn == null && resolved.pts == null) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className, children: "—" });
    }
    if (resolved.torn == null || resolved.pts == null || !price) {
      const fallback = resolved.torn != null ? formatMoney(resolved.torn) : formatExtensionPoints(resolved.pts);
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "span",
        {
          className,
          title: conversion2.loading ? "Loading Torn Xanax market price..." : void 0,
          children: fallback
        }
      );
    }
    const extensionPayout = formatExtensionPoints(resolved.pts);
    const tornPayoutLabel = formatMoney(resolved.torn);
    const averagePrice = formatMoney(price.averagePrice);
    const formula = formatPayoutFormula(resolved.pts, price.averagePrice);
    const modalTarget = getExtensionShadowMount();
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          className: `${styles$s.button} ${tornStyles.button} ${className ?? ""}`,
          title: `≈ ${extensionPayout} in PTS · click for details`,
          "aria-label": `${label2}: ${tornPayoutLabel}, about ${extensionPayout} in PTS. Click for conversion details.`,
          onMouseDown: (e) => e.stopPropagation(),
          onKeyDown: (e) => e.stopPropagation(),
          onClick: (e) => {
            e.stopPropagation();
            setModalOpen(true);
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: tornStyles.primaryDisplay, children: tornPayoutLabel }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: tornStyles.altDisplay, "aria-hidden": "true", children: extensionPayout })
          ]
        }
      ),
      modalOpen && reactDomExports.createPortal(
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          PayoutConversionModal,
          {
            extensionPayout,
            averagePrice,
            tornPayout: tornPayoutLabel,
            formula,
            utcDate: price.utcDate,
            onClose: () => setModalOpen(false)
          }
        ),
        modalTarget ?? document.body
      )
    ] });
  }
  function PayoutConversionModal({
    extensionPayout,
    averagePrice,
    tornPayout,
    formula,
    utcDate,
    onClose
  }) {
    reactExports.useEffect(() => {
      const handleKeyDown = (e) => {
        if (e.key === "Escape") onClose();
      };
      window.addEventListener("keydown", handleKeyDown);
      return () => window.removeEventListener("keydown", handleKeyDown);
    }, [onClose]);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `${contractStyles.overlay} ${contractStyles.overlayElevated}`,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onClose),
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-torn-primary-conversion-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-torn-primary-conversion-title", className: contractStyles.title, children: "Torn payout estimate" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$s.conversion, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$s.fromValue, children: extensionPayout }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$s.arrow, "aria-hidden": "true", children: "→" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$s.toValue, children: tornPayout })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$s.formulaLine, children: formula }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: styles$s.note, children: [
                "Based on Torn's daily average Xanax price of ",
                averagePrice,
                " (",
                utcDate,
                "). A rough guide, not an exact trade value."
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: contractStyles.actions, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  className: contractStyles.confirm,
                  onClick: onClose,
                  children: "Close"
                }
              ) })
            ]
          }
        )
      }
    );
  }
  const dialog$2 = "_dialog_9mjj2_1";
  const block$1 = "_block_9mjj2_11";
  const fieldHint$1 = "_fieldHint_9mjj2_21";
  const bountyStepDotActive = "_bountyStepDotActive_9mjj2_28";
  const bountyStepDotComplete = "_bountyStepDotComplete_9mjj2_34";
  const bountyStepLabelActive = "_bountyStepLabelActive_9mjj2_39";
  const bountyStepLabelComplete = "_bountyStepLabelComplete_9mjj2_40";
  const bountyStepConnectorFill = "_bountyStepConnectorFill_9mjj2_44";
  const bountyStepConnectorFillShoot = "_bountyStepConnectorFillShoot_9mjj2_49";
  const totalCostBlock = "_totalCostBlock_9mjj2_67";
  const costRow = "_costRow_9mjj2_76";
  const costRowLabel = "_costRowLabel_9mjj2_85";
  const costRowTotal = "_costRowTotal_9mjj2_90";
  const costRowValue = "_costRowValue_9mjj2_102";
  const fieldStyles$1 = {
    dialog: dialog$2,
    block: block$1,
    fieldHint: fieldHint$1,
    bountyStepDotActive,
    bountyStepDotComplete,
    bountyStepLabelActive,
    bountyStepLabelComplete,
    bountyStepConnectorFill,
    bountyStepConnectorFillShoot,
    totalCostBlock,
    costRow,
    costRowLabel,
    costRowTotal,
    costRowValue
  };
  function CostLine({
    label: label2,
    tornAmount,
    ptsAmount,
    payoutConversion,
    valueLabel,
    className
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${fieldStyles$1.costRow} ${className ?? ""} tlm-payout-hover-scope`, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: fieldStyles$1.costRowLabel, children: label2 }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        TornPrimaryValue,
        {
          tornAmount,
          ptsAmount,
          conversion: payoutConversion,
          label: valueLabel,
          className: fieldStyles$1.costRowValue
        }
      )
    ] });
  }
  function BountyCostBreakdown({
    quantity: quantity2,
    targetCount = 1,
    bountyValueTorn,
    totalPts,
    payoutConversion
  }) {
    const effectiveQuantity = quantity2 * targetCount;
    const bountyCostTorn = bountyValueTorn * effectiveQuantity;
    const tornFeeTorn = Math.round(bountyValueTorn * 0.5) * effectiveQuantity;
    const slotFeePts = BOUNTY_SERVICE_FEE_PTS * effectiveQuantity;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: fieldStyles$1.totalCostBlock, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        CostLine,
        {
          label: "Bounty Cost",
          tornAmount: bountyCostTorn,
          payoutConversion,
          valueLabel: "Bounty cost"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        CostLine,
        {
          label: "Torn Fee (50%)",
          tornAmount: tornFeeTorn,
          payoutConversion,
          valueLabel: "Torn placement fee"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        CostLine,
        {
          label: "Service Fee (150K PTS)",
          ptsAmount: slotFeePts,
          payoutConversion,
          valueLabel: "Bounty service fee"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: `${fieldStyles$1.costRow} ${fieldStyles$1.costRowTotal} tlm-payout-hover-scope`,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: fieldStyles$1.costRowLabel, children: "Total Cost" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              PayoutValue,
              {
                amount: totalPts,
                conversion: payoutConversion,
                label: "Bounty order total cost",
                className: fieldStyles$1.costRowValue
              }
            )
          ]
        }
      )
    ] });
  }
  const STEPS$4 = [
    { id: "targets", label: "Targets" },
    { id: "value", label: "Value" },
    { id: "quantity", label: "Quantity" }
  ];
  const STEP_SLIDE_MS$4 = 380;
  function stepIndex$4(step2) {
    return STEPS$4.findIndex((s) => s.id === step2);
  }
  function BountyOrderModal({
    onContinue,
    onCancel,
    payoutConversion,
    balance
  }) {
    var _a2;
    const inputRef = reactExports.useRef(null);
    const [step2, setStep] = reactExports.useState("targets");
    const [targetIdsInput, setTargetIdsInput] = reactExports.useState("");
    const [bountyValueInput, setBountyValueInput] = reactExports.useState("");
    const [quantityInput, setQuantityInput] = reactExports.useState("");
    const [error2, setError] = reactExports.useState(null);
    const [slideDirection, setSlideDirection] = reactExports.useState(
      "forward"
    );
    const [connectorShootIndex, setConnectorShootIndex] = reactExports.useState(
      null
    );
    const targetIds = reactExports.useMemo(
      () => parseBountyTargetIds(targetIdsInput),
      [targetIdsInput]
    );
    const bountyValueTorn = reactExports.useMemo(
      () => parseBountyValueInput(bountyValueInput),
      [bountyValueInput]
    );
    const quantity2 = reactExports.useMemo(
      () => parseBountyQuantityInput(quantityInput),
      [quantityInput]
    );
    const averageXanaxPrice = ((_a2 = payoutConversion.price) == null ? void 0 : _a2.averagePrice) ?? null;
    const targetCount = (targetIds == null ? void 0 : targetIds.length) ?? 0;
    const costBreakdown = reactExports.useMemo(() => {
      if (quantity2 === null || bountyValueTorn === null || targetCount === 0) {
        return null;
      }
      return computeBountyMultiTargetOrderTotalPts(
        quantity2,
        targetCount,
        bountyValueTorn,
        averageXanaxPrice,
        convertTornDollarsToScriptPoints
      );
    }, [quantity2, bountyValueTorn, targetCount, averageXanaxPrice]);
    const totalCostPts = (costBreakdown == null ? void 0 : costBreakdown.totalPts) ?? null;
    const maxAffordableQty = reactExports.useMemo(() => {
      if (bountyValueTorn === null || targetCount === 0) return null;
      const perUnit = computeBountyMultiTargetOrderTotalPts(
        1,
        targetCount,
        bountyValueTorn,
        averageXanaxPrice,
        convertTornDollarsToScriptPoints
      ).totalPts;
      if (perUnit == null || perUnit <= 0) return null;
      return Math.min(Math.floor(balance / perUnit), BOUNTY_QTY_MAX);
    }, [bountyValueTorn, targetCount, averageXanaxPrice, balance]);
    const activeStepIndex = stepIndex$4(step2);
    const showBack = step2 !== "targets";
    const canAdvanceTargets = targetIds !== null && targetIds.length > 0;
    const canAdvanceValue = bountyValueTorn !== null;
    const canAdvanceQuantity = quantity2 !== null && totalCostPts !== null;
    reactExports.useEffect(() => {
      const id2 = globalThis.setTimeout(() => {
        var _a3, _b, _c;
        (_a3 = inputRef.current) == null ? void 0 : _a3.focus();
        (_c = (_b = inputRef.current) == null ? void 0 : _b.select) == null ? void 0 : _c.call(_b);
      }, STEP_SLIDE_MS$4);
      return () => globalThis.clearTimeout(id2);
    }, [step2]);
    const goToStep = (next, direction) => {
      const prevIndex = stepIndex$4(step2);
      const nextIndex = stepIndex$4(next);
      if (direction === "forward" && nextIndex > prevIndex) {
        setConnectorShootIndex(prevIndex);
        globalThis.setTimeout(() => setConnectorShootIndex(null), 520);
      }
      setSlideDirection(direction);
      setStep(next);
    };
    const handleBack = () => {
      setError(null);
      if (step2 === "value") goToStep("targets", "back");
      else if (step2 === "quantity") goToStep("value", "back");
    };
    const handlePrimary = reactExports.useCallback(() => {
      if (step2 === "targets") {
        if (!canAdvanceTargets) {
          setError("Enter one or more target player IDs (comma-separated).");
          return;
        }
        setError(null);
        goToStep("value", "forward");
        return;
      }
      if (step2 === "value") {
        if (!canAdvanceValue) {
          setError("Enter a valid bounty value.");
          return;
        }
        setError(null);
        goToStep("quantity", "forward");
        return;
      }
      if (step2 === "quantity") {
        if (!canAdvanceQuantity || targetIds === null || bountyValueTorn === null) {
          setError(
            `Enter a whole number from ${BOUNTY_QTY_MIN.toLocaleString("en-US")} to ${BOUNTY_QTY_MAX.toLocaleString("en-US")}.`
          );
          return;
        }
        if (totalCostPts == null) {
          setError("Unable to calculate total cost.");
          return;
        }
        setError(null);
        onContinue({
          quantity: quantity2,
          targetIds,
          bountyValueTorn,
          totalCostPts
        });
      }
    }, [
      step2,
      canAdvanceTargets,
      canAdvanceValue,
      canAdvanceQuantity,
      targetIds,
      bountyValueTorn,
      quantity2,
      totalCostPts,
      onContinue
    ]);
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        if (showBack) handleBack();
        else onCancel();
      } else if (e.key === "Enter") {
        e.preventDefault();
        handlePrimary();
      }
    };
    const primaryLabel = step2 === "quantity" ? "Review" : "Continue";
    const primaryDisabled = step2 === "targets" ? !canAdvanceTargets : step2 === "value" ? !canAdvanceValue : !canAdvanceQuantity;
    const renderStepContent = () => {
      if (step2 === "targets") {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: fieldStyles$1.block, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: contractStyles.label, htmlFor: "tlm-bounty-targets", children: "Target ID(s)" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "input",
            {
              ref: inputRef,
              id: "tlm-bounty-targets",
              className: `${contractStyles.input} ${error2 && !canAdvanceTargets && targetIdsInput ? contractStyles.inputError : ""}`,
              type: "text",
              inputMode: "numeric",
              placeholder: "e.g. 2297468, 1169571",
              autoComplete: "off",
              value: targetIdsInput,
              onChange: (e) => {
                setTargetIdsInput(sanitizeBountyTargetIdsInput(e.target.value));
                setError(null);
              }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: fieldStyles$1.fieldHint, children: "Comma- or space-separated player IDs." })
        ] });
      }
      if (step2 === "value") {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: fieldStyles$1.block, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: contractStyles.label, htmlFor: "tlm-bounty-value", children: "Bounty value" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.inputWrap, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "input",
              {
                ref: inputRef,
                id: "tlm-bounty-value",
                className: `${contractStyles.input} ${contractStyles.inputWithPostfix} ${error2 && !canAdvanceValue && bountyValueInput ? contractStyles.inputError : ""}`,
                type: "text",
                inputMode: "decimal",
                placeholder: "e.g. 100k",
                autoComplete: "off",
                value: bountyValueInput,
                onChange: (e) => {
                  setBountyValueInput(sanitizeBountyValueInput(e.target.value));
                  setError(null);
                }
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: contractStyles.inputPostfix, "aria-hidden": "true", children: "Torn $" })
          ] })
        ] });
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: fieldStyles$1.block, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: contractStyles.label, htmlFor: "tlm-bounty-quantity", children: "Quantity" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          PtsAmountInput,
          {
            inputRef,
            id: "tlm-bounty-quantity",
            value: quantityInput,
            onChange: (next) => {
              setQuantityInput(next);
              setError(null);
            },
            max: BOUNTY_QTY_MAX,
            referenceMax: maxAffordableQty ?? 0,
            symbolLabel: "MAX",
            symbolDisabled: maxAffordableQty === null,
            sanitize: sanitizeBountyQuantityInput,
            inputMode: "numeric",
            placeholder: "e.g. 20",
            hasError: Boolean(error2 && !canAdvanceQuantity && quantityInput)
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: fieldStyles$1.fieldHint, children: [
          "Number of bounties per target (",
          BOUNTY_QTY_MIN,
          "–",
          BOUNTY_QTY_MAX.toLocaleString("en-US"),
          ").",
          targetCount > 1 ? ` Each of your ${targetCount} targets is a separate contract.` : ""
        ] }),
        canAdvanceQuantity && costBreakdown && bountyValueTorn !== null && quantity2 !== null && /* @__PURE__ */ jsxRuntimeExports.jsx(
          BountyCostBreakdown,
          {
            quantity: quantity2,
            targetCount,
            bountyValueTorn,
            totalPts: costBreakdown.totalPts,
            payoutConversion
          }
        )
      ] });
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `${contractStyles.overlay} ${contractStyles.overlayElevated}`,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onCancel),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: `${contractStyles.dialog} ${fieldStyles$1.dialog}`,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-bounty-order-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-bounty-order-title", className: contractStyles.title, children: "Place bounties" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.modalMain, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "ol",
                  {
                    className: summaryStyles.stepper,
                    "aria-label": "Bounty order progress",
                    children: STEPS$4.map((s, index) => {
                      const idx = stepIndex$4(s.id);
                      const complete = idx < activeStepIndex;
                      const active = idx === activeStepIndex;
                      const isLast = index === STEPS$4.length - 1;
                      return /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.stepperSegment, children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs(
                          "div",
                          {
                            className: `${summaryStyles.step} ${complete ? summaryStyles.stepComplete : ""} ${active ? summaryStyles.stepActive : ""}`,
                            children: [
                              /* @__PURE__ */ jsxRuntimeExports.jsx(
                                "span",
                                {
                                  className: `${summaryStyles.stepDot} ${active ? fieldStyles$1.bountyStepDotActive : ""} ${complete ? fieldStyles$1.bountyStepDotComplete : ""}`,
                                  "aria-hidden": "true"
                                }
                              ),
                              /* @__PURE__ */ jsxRuntimeExports.jsx(
                                "span",
                                {
                                  className: `${summaryStyles.stepLabel} ${active ? fieldStyles$1.bountyStepLabelActive : ""} ${complete ? fieldStyles$1.bountyStepLabelComplete : ""}`,
                                  children: s.label
                                }
                              )
                            ]
                          }
                        ),
                        !isLast && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.stepConnector, "aria-hidden": "true", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepConnectorTrack }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "span",
                            {
                              className: `${summaryStyles.stepConnectorFill} ${idx < activeStepIndex ? summaryStyles.stepConnectorFillComplete : ""} ${idx < activeStepIndex ? fieldStyles$1.bountyStepConnectorFill : ""} ${connectorShootIndex === idx ? `${fieldStyles$1.bountyStepConnectorFill} ${fieldStyles$1.bountyStepConnectorFillShoot}` : ""}`
                            }
                          )
                        ] })
                      ] }, s.id);
                    })
                  }
                ),
                step2 !== "targets" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.selectionSlot, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  BountyOrderSummary,
                  {
                    targetIds,
                    bountyValueTorn,
                    quantity: quantity2
                  }
                ) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.stepViewport, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "div",
                  {
                    className: `${summaryStyles.stepPanel} ${slideDirection === "forward" ? summaryStyles.stepPanelForward : summaryStyles.stepPanelBack}`,
                    children: renderStepContent()
                  },
                  step2
                ) }),
                error2 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.errorSlot, children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: summaryStyles.error, children: error2 }) })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${contractStyles.actions} ${summaryStyles.footer}`, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.cancel,
                    onClick: showBack ? handleBack : onCancel,
                    children: showBack ? "Back" : "Cancel"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.confirm,
                    onClick: handlePrimary,
                    disabled: primaryDisabled,
                    children: primaryLabel
                  }
                )
              ] })
            ]
          }
        )
      }
    );
  }
  function BountyConfirmModal({
    order,
    balance,
    payoutConversion,
    onConfirm,
    onBack,
    onAddBalance
  }) {
    const totalCost = order.totalCostPts;
    const insufficient = totalCost > balance;
    const remainingBalance = balance - totalCost;
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onBack();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `${contractStyles.overlay} ${contractStyles.overlayElevated} ${contractStyles.overlayElevatedTop}`,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onBack),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-bounty-confirm-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-bounty-confirm-title", className: contractStyles.title, children: "Confirm bounty order" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("ul", { className: summaryStyles.selectionSummary, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Quantity" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: summaryStyles.selectionValue, children: [
                    order.quantity.toLocaleString("en-US"),
                    order.targetIds.length > 1 ? " per target" : ""
                  ] })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Target(s)" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(BountyTargetLinks, { targetIds: order.targetIds }) })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Bounty value" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: summaryStyles.selectionValue, children: [
                    formatMoney(order.bountyValueTorn),
                    " each"
                  ] })
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostGroup, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceLabel, children: "Total cost" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "span",
                    {
                      className: `${summaryStyles.confirmBalanceValue} tlm-payout-hover-scope`,
                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                        PayoutValue,
                        {
                          amount: totalCost,
                          conversion: payoutConversion,
                          label: "Bounty order total cost"
                        }
                      )
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceLabel, children: "Remaining balance" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceValue, children: formatExtensionPoints(remainingBalance) })
                ] })
              ] }),
              insufficient && /* @__PURE__ */ jsxRuntimeExports.jsx(InsufficientBalanceMessage, { onAddBalance }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.cancel, onClick: onBack, children: "Back" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.confirm,
                    onClick: onConfirm,
                    disabled: insufficient,
                    children: "Confirm order"
                  }
                )
              ] })
            ]
          }
        )
      }
    );
  }
  const link$3 = "_link_c5pde_1";
  const styles$o = {
    link: link$3
  };
  function getTornCompanyUrl(companyId) {
    return `https://www.torn.com/joblist.php#!p=corpinfo&ID=${companyId}`;
  }
  function ProductivityBoostCompanyLink({
    companyId
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "a",
      {
        href: getTornCompanyUrl(companyId),
        className: styles$o.link,
        target: "_blank",
        rel: "noopener noreferrer",
        onClick: (e) => e.stopPropagation(),
        children: String(companyId)
      }
    );
  }
  const PLACEHOLDER$3 = "—";
  function SummaryValue$3({ children }) {
    if (children == null || children === false || typeof children === "string" && !children) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "span",
        {
          className: `${summaryStyles.selectionValue} ${summaryStyles.selectionValuePlaceholder}`,
          children: PLACEHOLDER$3
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${summaryStyles.selectionValue} ${summaryStyles.selectionValueWithLink}`, children });
  }
  function ProductivityBoostOrderSummary({
    companyId,
    pricePts
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "ul",
      {
        className: summaryStyles.selectionSummary,
        "aria-label": "Productivity boost summary",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Company" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryValue$3, { children: companyId != null ? /* @__PURE__ */ jsxRuntimeExports.jsx(ProductivityBoostCompanyLink, { companyId }) : null })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Price" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryValue$3, { children: pricePts != null ? formatExtensionPoints(pricePts) : null })
          ] })
        ]
      }
    );
  }
  const panel$4 = "_panel_1s77q_1";
  const collapsibleSection = "_collapsibleSection_1s77q_10";
  const sectionHeader = "_sectionHeader_1s77q_16";
  const sectionHeaderStart = "_sectionHeaderStart_1s77q_24";
  const sectionTitle = "_sectionTitle_1s77q_33";
  const sectionBadges = "_sectionBadges_1s77q_46";
  const sectionBadge = "_sectionBadge_1s77q_46";
  const sectionBadgeBlue = "_sectionBadgeBlue_1s77q_66";
  const sectionBadgeBlueCancel = "_sectionBadgeBlueCancel_1s77q_72";
  const sectionBadgeYellow = "_sectionBadgeYellow_1s77q_79";
  const sectionBadgePaused = "_sectionBadgePaused_1s77q_94";
  const sectionBadgeGreen = "_sectionBadgeGreen_1s77q_107";
  const sectionBadgeGreenCancel = "_sectionBadgeGreenCancel_1s77q_113";
  const sectionBadgeNeutral = "_sectionBadgeNeutral_1s77q_120";
  const sectionBadgeNeutralCancel = "_sectionBadgeNeutralCancel_1s77q_126";
  const sectionBadgeRed = "_sectionBadgeRed_1s77q_133";
  const sectionBadgeRedCancel = "_sectionBadgeRedCancel_1s77q_139";
  const sectionBadgeButton = "_sectionBadgeButton_1s77q_146";
  const sectionBadgeIcon = "_sectionBadgeIcon_1s77q_165";
  const sectionBadgeCount = "_sectionBadgeCount_1s77q_170";
  const sectionBadgeLabel = "_sectionBadgeLabel_1s77q_174";
  const sectionBadgeCountdown = "_sectionBadgeCountdown_1s77q_178";
  const sectionChevronButton = "_sectionChevronButton_1s77q_184";
  const sectionChevron = "_sectionChevron_1s77q_184";
  const sectionChevronExpanded = "_sectionChevronExpanded_1s77q_220";
  const sectionBody = "_sectionBody_1s77q_225";
  const openList = "_openList_1s77q_231";
  const openCard = "_openCard_1s77q_237";
  const cancelOrder = "_cancelOrder_1s77q_245";
  const openCardOwn = "_openCardOwn_1s77q_269";
  const openCardWithdraw = "_openCardWithdraw_1s77q_270";
  const openCardEmbargo = "_openCardEmbargo_1s77q_271";
  const openCardSimpleService = "_openCardSimpleService_1s77q_272";
  const openCardClosed = "_openCardClosed_1s77q_295";
  const openCardClickable = "_openCardClickable_1s77q_319";
  const openCardBadge = "_openCardBadge_1s77q_362";
  const openCardBadgeGreen = "_openCardBadgeGreen_1s77q_372";
  const openCardBadgeClosed = "_openCardBadgeClosed_1s77q_376";
  const openCardBadgePaused = "_openCardBadgePaused_1s77q_380";
  const sectionBadgeCompound = "_sectionBadgeCompound_1s77q_384";
  const sectionBadgeCompoundMain = "_sectionBadgeCompoundMain_1s77q_390";
  const sectionBadgeCompoundDismiss = "_sectionBadgeCompoundDismiss_1s77q_397";
  const servicesButtons = "_servicesButtons_1s77q_413";
  const openCardBadgeRed = "_openCardBadgeRed_1s77q_425";
  const openCardBadgeGray = "_openCardBadgeGray_1s77q_429";
  const inProgressBadge = "_inProgressBadge_1s77q_437";
  const inProgressDot = "_inProgressDot_1s77q_479";
  const openCardRows = "_openCardRows_1s77q_487";
  const openCardRow = "_openCardRow_1s77q_487";
  const openCardLabel = "_openCardLabel_1s77q_500";
  const openCardValue = "_openCardValue_1s77q_504";
  const form = "_form_1s77q_510";
  const field$1 = "_field_1s77q_520";
  const label$1 = "_label_1s77q_526";
  const labelText = "_labelText_1s77q_538";
  const labelPostfix = "_labelPostfix_1s77q_542";
  const labelPostfixWarning = "_labelPostfixWarning_1s77q_551";
  const timelyLossHint = "_timelyLossHint_1s77q_555";
  const totalRow = "_totalRow_1s77q_610";
  const totalLabel = "_totalLabel_1s77q_618";
  const totalValue = "_totalValue_1s77q_624";
  const error$2 = "_error_1s77q_631";
  const submit = "_submit_1s77q_637";
  const formDisabled = "_formDisabled_1s77q_661";
  const styles$n = {
    panel: panel$4,
    collapsibleSection,
    sectionHeader,
    sectionHeaderStart,
    sectionTitle,
    sectionBadges,
    sectionBadge,
    sectionBadgeBlue,
    sectionBadgeBlueCancel,
    sectionBadgeYellow,
    sectionBadgePaused,
    sectionBadgeGreen,
    sectionBadgeGreenCancel,
    sectionBadgeNeutral,
    sectionBadgeNeutralCancel,
    sectionBadgeRed,
    sectionBadgeRedCancel,
    sectionBadgeButton,
    sectionBadgeIcon,
    sectionBadgeCount,
    sectionBadgeLabel,
    sectionBadgeCountdown,
    sectionChevronButton,
    sectionChevron,
    sectionChevronExpanded,
    sectionBody,
    openList,
    openCard,
    cancelOrder,
    openCardOwn,
    openCardWithdraw,
    openCardEmbargo,
    openCardSimpleService,
    openCardClosed,
    openCardClickable,
    openCardBadge,
    openCardBadgeGreen,
    openCardBadgeClosed,
    openCardBadgePaused,
    sectionBadgeCompound,
    sectionBadgeCompoundMain,
    sectionBadgeCompoundDismiss,
    servicesButtons,
    openCardBadgeRed,
    openCardBadgeGray,
    inProgressBadge,
    inProgressDot,
    openCardRows,
    openCardRow,
    openCardLabel,
    openCardValue,
    form,
    field: field$1,
    label: label$1,
    labelText,
    labelPostfix,
    labelPostfixWarning,
    timelyLossHint,
    totalRow,
    totalLabel,
    totalValue,
    error: error$2,
    submit,
    formDisabled
  };
  const dialog$1 = "_dialog_wjgpw_1";
  const block = "_block_wjgpw_11";
  const fieldHint = "_fieldHint_wjgpw_21";
  const factionRow = "_factionRow_wjgpw_28";
  const factionButton = "_factionButton_wjgpw_37";
  const factionToggle = "_factionToggle_wjgpw_65";
  const reviewHint = "_reviewHint_wjgpw_90";
  const priceLabel = "_priceLabel_wjgpw_97";
  const priceLabelLeft = "_priceLabelLeft_wjgpw_106";
  const priceLabelRecommendedWarning = "_priceLabelRecommendedWarning_wjgpw_126";
  const fieldStyles = {
    dialog: dialog$1,
    block,
    fieldHint,
    factionRow,
    factionButton,
    factionToggle,
    reviewHint,
    priceLabel,
    priceLabelLeft,
    priceLabelRecommendedWarning
  };
  const STEPS$3 = [
    { id: "company", label: "Company" },
    { id: "price", label: "Price" },
    { id: "review", label: "Review" }
  ];
  const STEP_SLIDE_MS$3 = 380;
  function stepIndex$3(step2) {
    return STEPS$3.findIndex((s) => s.id === step2);
  }
  function ProductivityBoostOrderModal({
    onContinue,
    onCancel,
    payoutConversion,
    balance
  }) {
    var _a2;
    const inputRef = reactExports.useRef(null);
    const [step2, setStep] = reactExports.useState("company");
    const [companyIdInput, setCompanyIdInput] = reactExports.useState("");
    const [priceInput, setPriceInput] = reactExports.useState("");
    const [error2, setError] = reactExports.useState(null);
    const [slideDirection, setSlideDirection] = reactExports.useState(
      "forward"
    );
    const [connectorShootIndex, setConnectorShootIndex] = reactExports.useState(
      null
    );
    const companyId = reactExports.useMemo(
      () => parseCompanyIdInput(companyIdInput),
      [companyIdInput]
    );
    const pricePts = reactExports.useMemo(() => parsePriceInput(priceInput), [priceInput]);
    const averageXanaxPrice = ((_a2 = payoutConversion.price) == null ? void 0 : _a2.averagePrice) ?? null;
    const priceTornHint = reactExports.useMemo(() => {
      if (averageXanaxPrice == null || !priceInput.trim()) return null;
      const scriptAmount = evaluateNumericInput(priceInput);
      if (scriptAmount === null || !Number.isFinite(scriptAmount) || !Number.isInteger(scriptAmount) || scriptAmount <= 0) {
        return null;
      }
      const tornAmount = convertScriptDollarsToTornDollars(
        scriptAmount,
        averageXanaxPrice
      );
      return {
        tornAmount,
        tornHint: `(${formatMoney(tornAmount)})`,
        belowRecommended: tornAmount < RECOMMENDED_PRODUCTIVITY_PRICE_TORN
      };
    }, [averageXanaxPrice, priceInput]);
    const priceTorn = (priceTornHint == null ? void 0 : priceTornHint.tornAmount) ?? null;
    const totalCostPts = pricePts;
    const activeStepIndex = stepIndex$3(step2);
    const showBack = step2 !== "company";
    const canAdvanceCompany = companyId !== null;
    const canAdvancePrice = pricePts !== null && priceTorn !== null;
    reactExports.useEffect(() => {
      const id2 = globalThis.setTimeout(() => {
        var _a3, _b, _c;
        (_a3 = inputRef.current) == null ? void 0 : _a3.focus();
        (_c = (_b = inputRef.current) == null ? void 0 : _b.select) == null ? void 0 : _c.call(_b);
      }, STEP_SLIDE_MS$3);
      return () => globalThis.clearTimeout(id2);
    }, [step2]);
    const goToStep = (next, direction) => {
      const prevIndex = stepIndex$3(step2);
      const nextIndex = stepIndex$3(next);
      if (direction === "forward" && nextIndex > prevIndex) {
        setConnectorShootIndex(prevIndex);
        globalThis.setTimeout(() => setConnectorShootIndex(null), 520);
      }
      setSlideDirection(direction);
      setStep(next);
    };
    const handleBack = () => {
      setError(null);
      if (step2 === "price") goToStep("company", "back");
      else if (step2 === "review") goToStep("price", "back");
    };
    const handlePrimary = reactExports.useCallback(() => {
      if (step2 === "company") {
        if (!canAdvanceCompany) {
          setError("Enter a valid target company ID.");
          return;
        }
        setError(null);
        goToStep("price", "forward");
        return;
      }
      if (step2 === "price") {
        if (!canAdvancePrice) {
          setError("Enter a valid price in PTS.");
          return;
        }
        setError(null);
        goToStep("review", "forward");
        return;
      }
      if (step2 === "review") {
        if (companyId === null || priceTorn === null || totalCostPts === null) {
          setError("Complete all steps before reviewing.");
          return;
        }
        setError(null);
        onContinue({
          companyId,
          priceTorn,
          totalCostPts
        });
      }
    }, [
      step2,
      canAdvanceCompany,
      canAdvancePrice,
      companyId,
      priceTorn,
      totalCostPts,
      onContinue
    ]);
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        if (showBack) handleBack();
        else onCancel();
      } else if (e.key === "Enter") {
        e.preventDefault();
        handlePrimary();
      }
    };
    const primaryLabel = step2 === "review" ? "Review" : "Continue";
    const primaryDisabled = step2 === "company" ? !canAdvanceCompany : step2 === "price" ? !canAdvancePrice : !canAdvancePrice || companyId === null;
    const renderStepContent = () => {
      if (step2 === "company") {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: fieldStyles.block, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: contractStyles.label, htmlFor: "tlm-productivity-company-id", children: "Target company ID" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "input",
            {
              ref: inputRef,
              id: "tlm-productivity-company-id",
              className: `${contractStyles.input} ${error2 && !canAdvanceCompany && companyIdInput ? contractStyles.inputError : ""}`,
              type: "text",
              inputMode: "numeric",
              placeholder: "e.g. 1928374",
              autoComplete: "off",
              value: companyIdInput,
              onChange: (e) => {
                setCompanyIdInput(sanitizeCompanyIdInput(e.target.value));
                setError(null);
              }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: fieldStyles.fieldHint, children: "The Torn company ID to boost productivity for." })
        ] });
      }
      if (step2 === "price") {
        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: fieldStyles.block, children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$n.form, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.field, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "label",
            {
              className: `${styles$n.label} ${fieldStyles.priceLabel}`,
              htmlFor: "tlm-productivity-price",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: fieldStyles.priceLabelLeft, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.labelText, children: "Your Payment" }),
                  priceTornHint && /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "span",
                    {
                      className: `${styles$n.labelPostfix} ${priceTornHint.belowRecommended ? styles$n.labelPostfixWarning : ""}`,
                      children: priceTornHint.tornHint
                    }
                  )
                ] }),
                (!priceTornHint || priceTornHint.belowRecommended) && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: fieldStyles.priceLabelRecommendedWarning, children: "($35M+ recommended)" })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PtsAmountInput,
            {
              inputRef,
              id: "tlm-productivity-price",
              value: priceInput,
              onChange: (next) => {
                setPriceInput(next);
                setError(null);
              },
              max: BUYER_ORDER_PRICE_MAX,
              referenceMax: balance,
              sanitize: sanitizePriceInput,
              inputMode: "decimal",
              placeholder: "e.g. 100k, 0.4m",
              hasError: Boolean(error2 && !canAdvancePrice && priceInput)
            }
          )
        ] }) }) });
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: fieldStyles.block, children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: fieldStyles.reviewHint, children: "Everything looks good. Continue to review and pay." }) });
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `${contractStyles.overlay} ${contractStyles.overlayElevated}`,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onCancel),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: `${contractStyles.dialog} ${fieldStyles.dialog}`,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-productivity-boost-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-productivity-boost-title", className: contractStyles.title, children: "Productivity Boost" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.modalMain, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "ol",
                  {
                    className: summaryStyles.stepper,
                    "aria-label": "Productivity boost progress",
                    children: STEPS$3.map((s, index) => {
                      const idx = stepIndex$3(s.id);
                      const complete = idx < activeStepIndex;
                      const active = idx === activeStepIndex;
                      const isLast = index === STEPS$3.length - 1;
                      return /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.stepperSegment, children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs(
                          "div",
                          {
                            className: `${summaryStyles.step} ${complete ? summaryStyles.stepComplete : ""} ${active ? summaryStyles.stepActive : ""}`,
                            children: [
                              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepDot, "aria-hidden": "true" }),
                              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepLabel, children: s.label })
                            ]
                          }
                        ),
                        !isLast && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.stepConnector, "aria-hidden": "true", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepConnectorTrack }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "span",
                            {
                              className: `${summaryStyles.stepConnectorFill} ${idx < activeStepIndex ? summaryStyles.stepConnectorFillComplete : ""} ${connectorShootIndex === idx ? summaryStyles.stepConnectorFillShoot : ""}`
                            }
                          )
                        ] })
                      ] }, s.id);
                    })
                  }
                ),
                step2 !== "company" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.selectionSlot, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  ProductivityBoostOrderSummary,
                  {
                    companyId,
                    pricePts
                  }
                ) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.stepViewport, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "div",
                  {
                    className: `${summaryStyles.stepPanel} ${slideDirection === "forward" ? summaryStyles.stepPanelForward : summaryStyles.stepPanelBack}`,
                    children: renderStepContent()
                  },
                  step2
                ) }),
                error2 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.errorSlot, children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: summaryStyles.error, children: error2 }) })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${contractStyles.actions} ${summaryStyles.footer}`, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.cancel,
                    onClick: showBack ? handleBack : onCancel,
                    children: showBack ? "Back" : "Cancel"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.confirm,
                    onClick: handlePrimary,
                    disabled: primaryDisabled,
                    children: primaryLabel
                  }
                )
              ] })
            ]
          }
        )
      }
    );
  }
  function ProductivityBoostConfirmModal({
    order,
    balance,
    payoutConversion,
    onConfirm,
    onBack,
    onAddBalance
  }) {
    const totalCost = order.totalCostPts;
    const insufficient = totalCost > balance;
    const remainingBalance = balance - totalCost;
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onBack();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `${contractStyles.overlay} ${contractStyles.overlayElevated} ${contractStyles.overlayElevatedTop}`,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onBack),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-productivity-confirm-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-productivity-confirm-title", className: contractStyles.title, children: "Confirm productivity boost" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("ul", { className: summaryStyles.selectionSummary, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Company" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(ProductivityBoostCompanyLink, { companyId: order.companyId }) })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Price" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionValue, children: formatExtensionPoints(order.totalCostPts) })
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostGroup, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceLabel, children: "Total cost" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "span",
                    {
                      className: `${summaryStyles.confirmBalanceValue} tlm-payout-hover-scope`,
                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                        PayoutValue,
                        {
                          amount: totalCost,
                          conversion: payoutConversion,
                          label: "Productivity boost total cost"
                        }
                      )
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceLabel, children: "Remaining balance" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceValue, children: insufficient ? "—" : formatExtensionPoints(remainingBalance) })
                ] })
              ] }),
              insufficient && /* @__PURE__ */ jsxRuntimeExports.jsx(InsufficientBalanceMessage, { onAddBalance }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.cancel, onClick: onBack, children: "Back" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.confirm,
                    onClick: onConfirm,
                    disabled: insufficient,
                    children: "Confirm order"
                  }
                )
              ] })
            ]
          }
        )
      }
    );
  }
  const link$2 = "_link_1msbj_1";
  const styles$m = {
    link: link$2
  };
  function EmbargoTargetLink({ targetUserId }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "a",
      {
        href: getSellerProfileUrl(targetUserId),
        className: styles$m.link,
        target: "_blank",
        rel: "noopener noreferrer",
        onClick: (e) => e.stopPropagation(),
        children: String(targetUserId)
      }
    );
  }
  const PLACEHOLDER$2 = "—";
  function SummaryValue$2({ children }) {
    if (children == null || children === false || typeof children === "string" && !children) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "span",
        {
          className: `${summaryStyles.selectionValue} ${summaryStyles.selectionValuePlaceholder}`,
          children: PLACEHOLDER$2
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${summaryStyles.selectionValue} ${summaryStyles.selectionValueWithLink}`, children });
  }
  function EmbargoOrderSummary({
    targetUserId,
    pricePts
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("ul", { className: summaryStyles.selectionSummary, "aria-label": "Embargo summary", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Target" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryValue$2, { children: targetUserId != null ? /* @__PURE__ */ jsxRuntimeExports.jsx(EmbargoTargetLink, { targetUserId }) : null })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Price" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryValue$2, { children: pricePts != null ? formatExtensionPoints(pricePts) : null })
      ] })
    ] });
  }
  const STEPS$2 = [
    { id: "target", label: "Target" },
    { id: "price", label: "Your Payment" },
    { id: "review", label: "Review" }
  ];
  const STEP_SLIDE_MS$2 = 380;
  function stepIndex$2(step2) {
    return STEPS$2.findIndex((s) => s.id === step2);
  }
  function EmbargoOrderModal({
    onContinue,
    onCancel,
    payoutConversion,
    balance
  }) {
    var _a2;
    const inputRef = reactExports.useRef(null);
    const [step2, setStep] = reactExports.useState("target");
    const [targetIdInput, setTargetIdInput] = reactExports.useState("");
    const [priceInput, setPriceInput] = reactExports.useState("");
    const [error2, setError] = reactExports.useState(null);
    const [slideDirection, setSlideDirection] = reactExports.useState(
      "forward"
    );
    const [connectorShootIndex, setConnectorShootIndex] = reactExports.useState(
      null
    );
    const targetUserId = reactExports.useMemo(
      () => parseCompanyIdInput(targetIdInput),
      [targetIdInput]
    );
    const pricePts = reactExports.useMemo(() => parsePriceInput(priceInput), [priceInput]);
    const averageXanaxPrice = ((_a2 = payoutConversion.price) == null ? void 0 : _a2.averagePrice) ?? null;
    const priceTornHint = reactExports.useMemo(() => {
      if (averageXanaxPrice == null || !priceInput.trim()) return null;
      const scriptAmount = evaluateNumericInput(priceInput);
      if (scriptAmount === null || !Number.isFinite(scriptAmount) || !Number.isInteger(scriptAmount) || scriptAmount <= 0) {
        return null;
      }
      const tornAmount = convertScriptDollarsToTornDollars(
        scriptAmount,
        averageXanaxPrice
      );
      return {
        tornAmount,
        tornHint: `(${formatMoney(tornAmount)})`,
        belowRecommended: tornAmount < RECOMMENDED_EMBARGO_PRICE_TORN
      };
    }, [averageXanaxPrice, priceInput]);
    const priceTorn = (priceTornHint == null ? void 0 : priceTornHint.tornAmount) ?? null;
    const totalCostPts = pricePts;
    const activeStepIndex = stepIndex$2(step2);
    const showBack = step2 !== "target";
    const canAdvanceTarget = targetUserId !== null;
    const canAdvancePrice = pricePts !== null && priceTorn !== null;
    reactExports.useEffect(() => {
      const id2 = globalThis.setTimeout(() => {
        var _a3, _b, _c;
        (_a3 = inputRef.current) == null ? void 0 : _a3.focus();
        (_c = (_b = inputRef.current) == null ? void 0 : _b.select) == null ? void 0 : _c.call(_b);
      }, STEP_SLIDE_MS$2);
      return () => globalThis.clearTimeout(id2);
    }, [step2]);
    const goToStep = (next, direction) => {
      const prevIndex = stepIndex$2(step2);
      const nextIndex = stepIndex$2(next);
      if (direction === "forward" && nextIndex > prevIndex) {
        setConnectorShootIndex(prevIndex);
        globalThis.setTimeout(() => setConnectorShootIndex(null), 520);
      }
      setSlideDirection(direction);
      setStep(next);
    };
    const handleBack = () => {
      setError(null);
      if (step2 === "price") goToStep("target", "back");
      else if (step2 === "review") goToStep("price", "back");
    };
    const handlePrimary = reactExports.useCallback(() => {
      if (step2 === "target") {
        if (!canAdvanceTarget) {
          setError("Enter a valid target user ID.");
          return;
        }
        setError(null);
        goToStep("price", "forward");
        return;
      }
      if (step2 === "price") {
        if (!canAdvancePrice) {
          setError("Enter a valid price in PTS.");
          return;
        }
        setError(null);
        goToStep("review", "forward");
        return;
      }
      if (step2 === "review") {
        if (targetUserId === null || priceTorn === null || totalCostPts === null) {
          setError("Complete all steps before reviewing.");
          return;
        }
        setError(null);
        onContinue({
          targetUserId,
          priceTorn,
          totalCostPts
        });
      }
    }, [
      step2,
      canAdvanceTarget,
      canAdvancePrice,
      targetUserId,
      priceTorn,
      totalCostPts,
      onContinue
    ]);
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        if (showBack) handleBack();
        else onCancel();
      } else if (e.key === "Enter") {
        e.preventDefault();
        handlePrimary();
      }
    };
    const primaryLabel = step2 === "review" ? "Review" : "Continue";
    const primaryDisabled = step2 === "target" ? !canAdvanceTarget : step2 === "price" ? !canAdvancePrice : !canAdvancePrice || targetUserId === null;
    const renderStepContent = () => {
      if (step2 === "target") {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: fieldStyles.block, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: contractStyles.label, htmlFor: "tlm-embargo-target-id", children: "Target user ID" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "input",
            {
              ref: inputRef,
              id: "tlm-embargo-target-id",
              className: `${contractStyles.input} ${error2 && !canAdvanceTarget && targetIdInput ? contractStyles.inputError : ""}`,
              type: "text",
              inputMode: "numeric",
              placeholder: "e.g. 1928374",
              autoComplete: "off",
              value: targetIdInput,
              onChange: (e) => {
                setTargetIdInput(sanitizeCompanyIdInput(e.target.value));
                setError(null);
              }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: fieldStyles.fieldHint, children: "The Torn user (player) ID to embargo." })
        ] });
      }
      if (step2 === "price") {
        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: fieldStyles.block, children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$n.form, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.field, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "label",
            {
              className: `${styles$n.label} ${fieldStyles.priceLabel}`,
              htmlFor: "tlm-embargo-price",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: fieldStyles.priceLabelLeft, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.labelText, children: "Your Payment" }),
                  priceTornHint && /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "span",
                    {
                      className: `${styles$n.labelPostfix} ${priceTornHint.belowRecommended ? styles$n.labelPostfixWarning : ""}`,
                      children: priceTornHint.tornHint
                    }
                  )
                ] }),
                (!priceTornHint || priceTornHint.belowRecommended) && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: fieldStyles.priceLabelRecommendedWarning, children: "($5M+ recommended)" })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PtsAmountInput,
            {
              inputRef,
              id: "tlm-embargo-price",
              value: priceInput,
              onChange: (next) => {
                setPriceInput(next);
                setError(null);
              },
              max: BUYER_ORDER_PRICE_MAX,
              referenceMax: balance,
              sanitize: sanitizePriceInput,
              inputMode: "decimal",
              placeholder: "e.g. 100k, 0.4m",
              hasError: Boolean(error2 && !canAdvancePrice && priceInput)
            }
          )
        ] }) }) });
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: fieldStyles.block, children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: fieldStyles.reviewHint, children: "Everything looks good. Continue to review and pay." }) });
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `${contractStyles.overlay} ${contractStyles.overlayElevated}`,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onCancel),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: `${contractStyles.dialog} ${fieldStyles.dialog}`,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-embargo-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-embargo-title", className: contractStyles.title, children: "Embargo" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.modalMain, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "ol",
                  {
                    className: `${summaryStyles.stepper} ${summaryStyles.stepperRed}`,
                    "aria-label": "Embargo progress",
                    children: STEPS$2.map((s, index) => {
                      const idx = stepIndex$2(s.id);
                      const complete = idx < activeStepIndex;
                      const active = idx === activeStepIndex;
                      const isLast = index === STEPS$2.length - 1;
                      return /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.stepperSegment, children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs(
                          "div",
                          {
                            className: `${summaryStyles.step} ${complete ? summaryStyles.stepComplete : ""} ${active ? summaryStyles.stepActive : ""}`,
                            children: [
                              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepDot, "aria-hidden": "true" }),
                              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepLabel, children: s.label })
                            ]
                          }
                        ),
                        !isLast && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.stepConnector, "aria-hidden": "true", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepConnectorTrack }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "span",
                            {
                              className: `${summaryStyles.stepConnectorFill} ${idx < activeStepIndex ? summaryStyles.stepConnectorFillComplete : ""} ${connectorShootIndex === idx ? summaryStyles.stepConnectorFillShoot : ""}`
                            }
                          )
                        ] })
                      ] }, s.id);
                    })
                  }
                ),
                step2 !== "target" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.selectionSlot, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  EmbargoOrderSummary,
                  {
                    targetUserId,
                    pricePts
                  }
                ) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.stepViewport, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "div",
                  {
                    className: `${summaryStyles.stepPanel} ${slideDirection === "forward" ? summaryStyles.stepPanelForward : summaryStyles.stepPanelBack}`,
                    children: renderStepContent()
                  },
                  step2
                ) }),
                error2 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.errorSlot, children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: summaryStyles.error, children: error2 }) })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${contractStyles.actions} ${summaryStyles.footer}`, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.cancel,
                    onClick: showBack ? handleBack : onCancel,
                    children: showBack ? "Back" : "Cancel"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.confirm,
                    onClick: handlePrimary,
                    disabled: primaryDisabled,
                    children: primaryLabel
                  }
                )
              ] })
            ]
          }
        )
      }
    );
  }
  function EmbargoConfirmModal({
    order,
    balance,
    payoutConversion,
    onConfirm,
    onBack,
    onAddBalance
  }) {
    const totalCost = order.totalCostPts;
    const insufficient = totalCost > balance;
    const remainingBalance = balance - totalCost;
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onBack();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `${contractStyles.overlay} ${contractStyles.overlayElevated} ${contractStyles.overlayElevatedTop}`,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onBack),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-embargo-confirm-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-embargo-confirm-title", className: contractStyles.title, children: "Confirm embargo" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("ul", { className: summaryStyles.selectionSummary, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Target" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(EmbargoTargetLink, { targetUserId: order.targetUserId }) })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Price" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionValue, children: formatExtensionPoints(order.totalCostPts) })
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostGroup, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceLabel, children: "Total cost" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "span",
                    {
                      className: `${summaryStyles.confirmBalanceValue} tlm-payout-hover-scope`,
                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                        PayoutValue,
                        {
                          amount: totalCost,
                          conversion: payoutConversion,
                          label: "Embargo total cost"
                        }
                      )
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceLabel, children: "Remaining balance" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceValue, children: insufficient ? "—" : formatExtensionPoints(remainingBalance) })
                ] })
              ] }),
              insufficient && /* @__PURE__ */ jsxRuntimeExports.jsx(InsufficientBalanceMessage, { onAddBalance }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.cancel, onClick: onBack, children: "Back" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.confirm,
                    onClick: onConfirm,
                    disabled: insufficient,
                    children: "Confirm order"
                  }
                )
              ] })
            ]
          }
        )
      }
    );
  }
  const link$1 = "_link_1msbj_1";
  const styles$l = {
    link: link$1
  };
  function FlightDelayTargetLink({
    targetUserId
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "a",
      {
        href: getSellerProfileUrl(targetUserId),
        className: styles$l.link,
        target: "_blank",
        rel: "noopener noreferrer",
        onClick: (e) => e.stopPropagation(),
        children: String(targetUserId)
      }
    );
  }
  const PLACEHOLDER$1 = "—";
  function SummaryValue$1({ children }) {
    if (children == null || children === false || typeof children === "string" && !children) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "span",
        {
          className: `${summaryStyles.selectionValue} ${summaryStyles.selectionValuePlaceholder}`,
          children: PLACEHOLDER$1
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${summaryStyles.selectionValue} ${summaryStyles.selectionValueWithLink}`, children });
  }
  function FlightDelayOrderSummary({
    targetUserId,
    pricePts
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("ul", { className: summaryStyles.selectionSummary, "aria-label": "Flight delay summary", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Target" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryValue$1, { children: targetUserId != null ? /* @__PURE__ */ jsxRuntimeExports.jsx(FlightDelayTargetLink, { targetUserId }) : null })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Price" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryValue$1, { children: pricePts != null ? formatExtensionPoints(pricePts) : null })
      ] })
    ] });
  }
  const STEPS$1 = [
    { id: "target", label: "Target" },
    { id: "price", label: "Your Payment" },
    { id: "review", label: "Review" }
  ];
  const STEP_SLIDE_MS$1 = 380;
  function stepIndex$1(step2) {
    return STEPS$1.findIndex((s) => s.id === step2);
  }
  function FlightDelayOrderModal({
    onContinue,
    onCancel,
    payoutConversion,
    balance
  }) {
    var _a2;
    const inputRef = reactExports.useRef(null);
    const [step2, setStep] = reactExports.useState("target");
    const [targetIdInput, setTargetIdInput] = reactExports.useState("");
    const [priceInput, setPriceInput] = reactExports.useState("");
    const [error2, setError] = reactExports.useState(null);
    const [slideDirection, setSlideDirection] = reactExports.useState(
      "forward"
    );
    const [connectorShootIndex, setConnectorShootIndex] = reactExports.useState(
      null
    );
    const targetUserId = reactExports.useMemo(
      () => parseCompanyIdInput(targetIdInput),
      [targetIdInput]
    );
    const pricePts = reactExports.useMemo(() => parsePriceInput(priceInput), [priceInput]);
    const averageXanaxPrice = ((_a2 = payoutConversion.price) == null ? void 0 : _a2.averagePrice) ?? null;
    const priceTornHint = reactExports.useMemo(() => {
      if (averageXanaxPrice == null || !priceInput.trim()) return null;
      const scriptAmount = evaluateNumericInput(priceInput);
      if (scriptAmount === null || !Number.isFinite(scriptAmount) || !Number.isInteger(scriptAmount) || scriptAmount <= 0) {
        return null;
      }
      const tornAmount = convertScriptDollarsToTornDollars(
        scriptAmount,
        averageXanaxPrice
      );
      return {
        tornAmount,
        tornHint: `(${formatMoney(tornAmount)})`,
        belowRecommended: tornAmount < RECOMMENDED_FLIGHT_DELAY_PRICE_TORN
      };
    }, [averageXanaxPrice, priceInput]);
    const priceTorn = (priceTornHint == null ? void 0 : priceTornHint.tornAmount) ?? null;
    const totalCostPts = pricePts;
    const activeStepIndex = stepIndex$1(step2);
    const showBack = step2 !== "target";
    const canAdvanceTarget = targetUserId !== null;
    const canAdvancePrice = pricePts !== null && priceTorn !== null;
    reactExports.useEffect(() => {
      const id2 = globalThis.setTimeout(() => {
        var _a3, _b, _c;
        (_a3 = inputRef.current) == null ? void 0 : _a3.focus();
        (_c = (_b = inputRef.current) == null ? void 0 : _b.select) == null ? void 0 : _c.call(_b);
      }, STEP_SLIDE_MS$1);
      return () => globalThis.clearTimeout(id2);
    }, [step2]);
    const goToStep = (next, direction) => {
      const prevIndex = stepIndex$1(step2);
      const nextIndex = stepIndex$1(next);
      if (direction === "forward" && nextIndex > prevIndex) {
        setConnectorShootIndex(prevIndex);
        globalThis.setTimeout(() => setConnectorShootIndex(null), 520);
      }
      setSlideDirection(direction);
      setStep(next);
    };
    const handleBack = () => {
      setError(null);
      if (step2 === "price") goToStep("target", "back");
      else if (step2 === "review") goToStep("price", "back");
    };
    const handlePrimary = reactExports.useCallback(() => {
      if (step2 === "target") {
        if (!canAdvanceTarget) {
          setError("Enter a valid target user ID.");
          return;
        }
        setError(null);
        goToStep("price", "forward");
        return;
      }
      if (step2 === "price") {
        if (!canAdvancePrice) {
          setError("Enter a valid price in PTS.");
          return;
        }
        setError(null);
        goToStep("review", "forward");
        return;
      }
      if (step2 === "review") {
        if (targetUserId === null || priceTorn === null || totalCostPts === null) {
          setError("Complete all steps before reviewing.");
          return;
        }
        setError(null);
        onContinue({
          targetUserId,
          priceTorn,
          totalCostPts
        });
      }
    }, [
      step2,
      canAdvanceTarget,
      canAdvancePrice,
      targetUserId,
      priceTorn,
      totalCostPts,
      onContinue
    ]);
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        if (showBack) handleBack();
        else onCancel();
      } else if (e.key === "Enter") {
        e.preventDefault();
        handlePrimary();
      }
    };
    const primaryLabel = step2 === "review" ? "Review" : "Continue";
    const primaryDisabled = step2 === "target" ? !canAdvanceTarget : step2 === "price" ? !canAdvancePrice : !canAdvancePrice || targetUserId === null;
    const renderStepContent = () => {
      if (step2 === "target") {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: fieldStyles.block, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "label",
            {
              className: contractStyles.label,
              htmlFor: "tlm-flight-delay-target-id",
              children: "Target user ID"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "input",
            {
              ref: inputRef,
              id: "tlm-flight-delay-target-id",
              className: `${contractStyles.input} ${error2 && !canAdvanceTarget && targetIdInput ? contractStyles.inputError : ""}`,
              type: "text",
              inputMode: "numeric",
              placeholder: "e.g. 1928374",
              autoComplete: "off",
              value: targetIdInput,
              onChange: (e) => {
                setTargetIdInput(sanitizeCompanyIdInput(e.target.value));
                setError(null);
              }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: fieldStyles.fieldHint, children: "The Torn user (player) ID to delay." })
        ] });
      }
      if (step2 === "price") {
        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: fieldStyles.block, children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$n.form, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.field, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "label",
            {
              className: `${styles$n.label} ${fieldStyles.priceLabel}`,
              htmlFor: "tlm-flight-delay-price",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: fieldStyles.priceLabelLeft, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.labelText, children: "Your Payment" }),
                  priceTornHint && /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "span",
                    {
                      className: `${styles$n.labelPostfix} ${priceTornHint.belowRecommended ? styles$n.labelPostfixWarning : ""}`,
                      children: priceTornHint.tornHint
                    }
                  )
                ] }),
                (!priceTornHint || priceTornHint.belowRecommended) && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: fieldStyles.priceLabelRecommendedWarning, children: "($15M+ recommended)" })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PtsAmountInput,
            {
              inputRef,
              id: "tlm-flight-delay-price",
              value: priceInput,
              onChange: (next) => {
                setPriceInput(next);
                setError(null);
              },
              max: BUYER_ORDER_PRICE_MAX,
              referenceMax: balance,
              sanitize: sanitizePriceInput,
              inputMode: "decimal",
              placeholder: "e.g. 100k, 0.4m",
              hasError: Boolean(error2 && !canAdvancePrice && priceInput)
            }
          )
        ] }) }) });
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: fieldStyles.block, children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: fieldStyles.reviewHint, children: "Everything looks good. Continue to review and pay." }) });
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `${contractStyles.overlay} ${contractStyles.overlayElevated}`,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onCancel),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: `${contractStyles.dialog} ${fieldStyles.dialog}`,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-flight-delay-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-flight-delay-title", className: contractStyles.title, children: "Flight Delay" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.modalMain, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "ol",
                  {
                    className: `${summaryStyles.stepper} ${summaryStyles.stepperRed}`,
                    "aria-label": "Flight delay progress",
                    children: STEPS$1.map((s, index) => {
                      const idx = stepIndex$1(s.id);
                      const complete = idx < activeStepIndex;
                      const active = idx === activeStepIndex;
                      const isLast = index === STEPS$1.length - 1;
                      return /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.stepperSegment, children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs(
                          "div",
                          {
                            className: `${summaryStyles.step} ${complete ? summaryStyles.stepComplete : ""} ${active ? summaryStyles.stepActive : ""}`,
                            children: [
                              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepDot, "aria-hidden": "true" }),
                              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepLabel, children: s.label })
                            ]
                          }
                        ),
                        !isLast && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.stepConnector, "aria-hidden": "true", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepConnectorTrack }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "span",
                            {
                              className: `${summaryStyles.stepConnectorFill} ${idx < activeStepIndex ? summaryStyles.stepConnectorFillComplete : ""} ${connectorShootIndex === idx ? summaryStyles.stepConnectorFillShoot : ""}`
                            }
                          )
                        ] })
                      ] }, s.id);
                    })
                  }
                ),
                step2 !== "target" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.selectionSlot, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  FlightDelayOrderSummary,
                  {
                    targetUserId,
                    pricePts
                  }
                ) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.stepViewport, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "div",
                  {
                    className: `${summaryStyles.stepPanel} ${slideDirection === "forward" ? summaryStyles.stepPanelForward : summaryStyles.stepPanelBack}`,
                    children: renderStepContent()
                  },
                  step2
                ) }),
                error2 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.errorSlot, children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: summaryStyles.error, children: error2 }) })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${contractStyles.actions} ${summaryStyles.footer}`, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.cancel,
                    onClick: showBack ? handleBack : onCancel,
                    children: showBack ? "Back" : "Cancel"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.confirm,
                    onClick: handlePrimary,
                    disabled: primaryDisabled,
                    children: primaryLabel
                  }
                )
              ] })
            ]
          }
        )
      }
    );
  }
  function FlightDelayConfirmModal({
    order,
    balance,
    payoutConversion,
    onConfirm,
    onBack,
    onAddBalance
  }) {
    const totalCost = order.totalCostPts;
    const insufficient = totalCost > balance;
    const remainingBalance = balance - totalCost;
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onBack();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `${contractStyles.overlay} ${contractStyles.overlayElevated} ${contractStyles.overlayElevatedTop}`,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onBack),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-flight-delay-confirm-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-flight-delay-confirm-title", className: contractStyles.title, children: "Confirm flight delay" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("ul", { className: summaryStyles.selectionSummary, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Target" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(FlightDelayTargetLink, { targetUserId: order.targetUserId }) })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Price" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionValue, children: formatExtensionPoints(order.totalCostPts) })
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostGroup, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceLabel, children: "Total cost" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "span",
                    {
                      className: `${summaryStyles.confirmBalanceValue} tlm-payout-hover-scope`,
                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                        PayoutValue,
                        {
                          amount: totalCost,
                          conversion: payoutConversion,
                          label: "Flight delay total cost"
                        }
                      )
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceLabel, children: "Remaining balance" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceValue, children: insufficient ? "—" : formatExtensionPoints(remainingBalance) })
                ] })
              ] }),
              insufficient && /* @__PURE__ */ jsxRuntimeExports.jsx(InsufficientBalanceMessage, { onAddBalance }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.cancel, onClick: onBack, children: "Back" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.confirm,
                    onClick: onConfirm,
                    disabled: insufficient,
                    children: "Confirm order"
                  }
                )
              ] })
            ]
          }
        )
      }
    );
  }
  const link = "_link_18ay8_1";
  const styles$k = {
    link
  };
  function SimpleServiceTargetLink({
    targetUserId
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "a",
      {
        href: getSellerProfileUrl(targetUserId),
        className: styles$k.link,
        target: "_blank",
        rel: "noopener noreferrer",
        onClick: (e) => e.stopPropagation(),
        children: String(targetUserId)
      }
    );
  }
  const PLACEHOLDER = "—";
  function SummaryValue({ children }) {
    if (children == null || children === false || typeof children === "string" && !children) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "span",
        {
          className: `${summaryStyles.selectionValue} ${summaryStyles.selectionValuePlaceholder}`,
          children: PLACEHOLDER
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${summaryStyles.selectionValue} ${summaryStyles.selectionValueWithLink}`, children });
  }
  function SimpleServiceOrderSummary({
    label: label2,
    targetUserIds,
    factionId,
    pricePts
  }) {
    const targetContent = factionId != null ? `Faction ${factionId} (${targetUserIds.length} member${targetUserIds.length === 1 ? "" : "s"})` : targetUserIds.length === 1 ? /* @__PURE__ */ jsxRuntimeExports.jsx(SimpleServiceTargetLink, { targetUserId: targetUserIds[0] }) : targetUserIds.length > 1 ? `${targetUserIds.length} targets` : null;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("ul", { className: summaryStyles.selectionSummary, "aria-label": `${label2} summary`, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: factionId != null ? "Faction" : "Target" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryValue, { children: targetContent })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Price each" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SummaryValue, { children: pricePts != null ? formatExtensionPoints(pricePts) : null })
      ] })
    ] });
  }
  const STEPS = [
    { id: "target", label: "Target" },
    { id: "price", label: "Your Payment" },
    { id: "review", label: "Review" }
  ];
  const STEP_SLIDE_MS = 380;
  function stepIndex(step2) {
    return STEPS.findIndex((s) => s.id === step2);
  }
  function SimpleServiceOrderModal({
    config,
    currentUserXid,
    onContinue,
    onCancel,
    payoutConversion,
    onResolveFactionMembers,
    balance
  }) {
    var _a2;
    const inputRef = reactExports.useRef(null);
    const [step2, setStep] = reactExports.useState("target");
    const [targetIdInput, setTargetIdInput] = reactExports.useState(
      () => config.autofillSelf && currentUserXid != null && currentUserXid > 0 ? String(currentUserXid) : ""
    );
    const [factionMode, setFactionMode] = reactExports.useState(false);
    const [factionIdInput, setFactionIdInput] = reactExports.useState("");
    const [resolving, setResolving] = reactExports.useState(false);
    const [factionTargets, setFactionTargets] = reactExports.useState(null);
    const [priceInput, setPriceInput] = reactExports.useState("");
    const [error2, setError] = reactExports.useState(null);
    const [slideDirection, setSlideDirection] = reactExports.useState(
      "forward"
    );
    const [connectorShootIndex, setConnectorShootIndex] = reactExports.useState(
      null
    );
    const targetUserId = reactExports.useMemo(
      () => parseCompanyIdInput(targetIdInput),
      [targetIdInput]
    );
    const factionId = reactExports.useMemo(
      () => parseCompanyIdInput(factionIdInput),
      [factionIdInput]
    );
    const useFaction = config.allowFactionTarget === true && factionMode && factionIdInput.trim().length > 0;
    const pricePts = reactExports.useMemo(() => parsePriceInput(priceInput), [priceInput]);
    const averageXanaxPrice = ((_a2 = payoutConversion.price) == null ? void 0 : _a2.averagePrice) ?? null;
    const priceTornHint = reactExports.useMemo(() => {
      if (averageXanaxPrice == null || !priceInput.trim()) return null;
      const scriptAmount = evaluateNumericInput(priceInput);
      if (scriptAmount === null || !Number.isFinite(scriptAmount) || !Number.isInteger(scriptAmount) || scriptAmount <= 0) {
        return null;
      }
      const tornAmount = convertScriptDollarsToTornDollars(
        scriptAmount,
        averageXanaxPrice
      );
      return {
        tornAmount,
        tornHint: `(${formatMoney(tornAmount)})`,
        belowRecommended: tornAmount < config.recommendedTorn
      };
    }, [averageXanaxPrice, priceInput, config.recommendedTorn]);
    const priceTorn = (priceTornHint == null ? void 0 : priceTornHint.tornAmount) ?? null;
    const totalCostPts = pricePts;
    const activeStepIndex = stepIndex(step2);
    const showBack = step2 !== "target";
    const canAdvanceTarget = useFaction ? factionId !== null : targetUserId !== null;
    const canAdvancePrice = pricePts !== null && priceTorn !== null;
    reactExports.useEffect(() => {
      const id2 = globalThis.setTimeout(() => {
        var _a3, _b, _c;
        (_a3 = inputRef.current) == null ? void 0 : _a3.focus();
        (_c = (_b = inputRef.current) == null ? void 0 : _b.select) == null ? void 0 : _c.call(_b);
      }, STEP_SLIDE_MS);
      return () => globalThis.clearTimeout(id2);
    }, [step2]);
    const goToStep = (next, direction) => {
      const prevIndex = stepIndex(step2);
      const nextIndex = stepIndex(next);
      if (direction === "forward" && nextIndex > prevIndex) {
        setConnectorShootIndex(prevIndex);
        globalThis.setTimeout(() => setConnectorShootIndex(null), 520);
      }
      setSlideDirection(direction);
      setStep(next);
    };
    const handleBack = () => {
      setError(null);
      if (step2 === "price") goToStep("target", "back");
      else if (step2 === "review") goToStep("price", "back");
    };
    const handlePrimary = async () => {
      if (resolving) return;
      if (step2 === "target") {
        if (!canAdvanceTarget) {
          setError(
            useFaction ? "Enter a valid faction ID." : "Enter a valid target user ID."
          );
          return;
        }
        if (useFaction) {
          if (!onResolveFactionMembers || factionId === null) return;
          setResolving(true);
          setError(null);
          try {
            const ids = await onResolveFactionMembers(factionId);
            if (ids.length === 0) {
              setError("No members found for that faction.");
              return;
            }
            setFactionTargets(ids);
            goToStep("price", "forward");
          } catch (e) {
            setError(
              e instanceof Error ? e.message : "Could not load faction members."
            );
          } finally {
            setResolving(false);
          }
          return;
        }
        setFactionTargets(null);
        setError(null);
        goToStep("price", "forward");
        return;
      }
      if (step2 === "price") {
        if (!canAdvancePrice) {
          setError("Enter a valid price in PTS.");
          return;
        }
        setError(null);
        goToStep("review", "forward");
        return;
      }
      if (step2 === "review") {
        const targets = useFaction ? factionTargets ?? [] : targetUserId !== null ? [targetUserId] : [];
        if (targets.length === 0 || priceTorn === null || totalCostPts === null) {
          setError("Complete all steps before reviewing.");
          return;
        }
        setError(null);
        onContinue({
          kind: config.id,
          targetUserIds: targets,
          priceTorn,
          totalCostPts
        });
      }
    };
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        if (showBack) handleBack();
        else onCancel();
      } else if (e.key === "Enter") {
        e.preventDefault();
        handlePrimary();
      }
    };
    const reviewTargetCount = useFaction ? (factionTargets == null ? void 0 : factionTargets.length) ?? 0 : targetUserId !== null ? 1 : 0;
    const primaryLabel = step2 === "target" && resolving ? "Loading…" : step2 === "review" ? "Review" : "Continue";
    const primaryDisabled = step2 === "target" ? !canAdvanceTarget || resolving : step2 === "price" ? !canAdvancePrice : !canAdvancePrice || reviewTargetCount === 0;
    const renderStepContent = () => {
      if (step2 === "target") {
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: fieldStyles.block, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "label",
            {
              className: contractStyles.label,
              htmlFor: "tlm-simple-service-target-id",
              children: "Target user ID"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "input",
            {
              ref: inputRef,
              id: "tlm-simple-service-target-id",
              className: `${contractStyles.input} ${error2 && !canAdvanceTarget && !useFaction && targetIdInput ? contractStyles.inputError : ""}`,
              type: "text",
              inputMode: "numeric",
              placeholder: "e.g. 1928374",
              autoComplete: "off",
              disabled: useFaction,
              value: targetIdInput,
              onChange: (e) => {
                setTargetIdInput(sanitizeCompanyIdInput(e.target.value));
                setError(null);
              }
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: fieldStyles.fieldHint, children: useFaction ? "Targeting a whole faction — the single user is ignored." : "The Torn user (player) ID to target." }),
          config.allowFactionTarget && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: fieldStyles.factionRow, children: factionMode ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "label",
              {
                className: contractStyles.label,
                htmlFor: "tlm-simple-service-faction-id",
                children: "Target faction ID"
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "input",
              {
                id: "tlm-simple-service-faction-id",
                className: `${contractStyles.input} ${error2 && useFaction && factionId === null && factionIdInput ? contractStyles.inputError : ""}`,
                type: "text",
                inputMode: "numeric",
                placeholder: "e.g. 5021",
                autoComplete: "off",
                value: factionIdInput,
                onChange: (e) => {
                  setFactionIdInput(
                    sanitizeCompanyIdInput(e.target.value)
                  );
                  setFactionTargets(null);
                  setError(null);
                }
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                type: "button",
                className: fieldStyles.factionToggle,
                onClick: () => {
                  setFactionMode(false);
                  setFactionIdInput("");
                  setFactionTargets(null);
                  setError(null);
                },
                children: "Target a single user instead"
              }
            )
          ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: fieldStyles.factionButton,
              onClick: () => {
                setFactionMode(true);
                setError(null);
              },
              children: "Target Faction?"
            }
          ) })
        ] });
      }
      if (step2 === "price") {
        return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: fieldStyles.block, children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$n.form, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.field, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "label",
            {
              className: `${styles$n.label} ${fieldStyles.priceLabel}`,
              htmlFor: "tlm-simple-service-price",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: fieldStyles.priceLabelLeft, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.labelText, children: "Your Payment" }),
                  priceTornHint && /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "span",
                    {
                      className: `${styles$n.labelPostfix} ${priceTornHint.belowRecommended ? styles$n.labelPostfixWarning : ""}`,
                      children: priceTornHint.tornHint
                    }
                  )
                ] }),
                (!priceTornHint || priceTornHint.belowRecommended) && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: fieldStyles.priceLabelRecommendedWarning, children: [
                  "(",
                  config.recommendedHint,
                  ")"
                ] })
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PtsAmountInput,
            {
              inputRef,
              id: "tlm-simple-service-price",
              value: priceInput,
              onChange: (next) => {
                setPriceInput(next);
                setError(null);
              },
              max: BUYER_ORDER_PRICE_MAX,
              referenceMax: balance,
              sanitize: sanitizePriceInput,
              inputMode: "decimal",
              placeholder: "e.g. 100k, 0.4m",
              hasError: Boolean(error2 && !canAdvancePrice && priceInput)
            }
          )
        ] }) }) });
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: fieldStyles.block, children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: fieldStyles.reviewHint, children: "Everything looks good. Continue to review and pay." }) });
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `${contractStyles.overlay} ${contractStyles.overlayElevated}`,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onCancel),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: `${contractStyles.dialog} ${fieldStyles.dialog}`,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-simple-service-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-simple-service-title", className: contractStyles.title, children: config.label }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.modalMain, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "ol",
                  {
                    className: `${summaryStyles.stepper} ${summaryStyles.stepperGray}`,
                    "aria-label": `${config.label} progress`,
                    children: STEPS.map((s, index) => {
                      const idx = stepIndex(s.id);
                      const complete = idx < activeStepIndex;
                      const active = idx === activeStepIndex;
                      const isLast = index === STEPS.length - 1;
                      return /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.stepperSegment, children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs(
                          "div",
                          {
                            className: `${summaryStyles.step} ${complete ? summaryStyles.stepComplete : ""} ${active ? summaryStyles.stepActive : ""}`,
                            children: [
                              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepDot, "aria-hidden": "true" }),
                              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepLabel, children: s.label })
                            ]
                          }
                        ),
                        !isLast && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.stepConnector, "aria-hidden": "true", children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.stepConnectorTrack }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "span",
                            {
                              className: `${summaryStyles.stepConnectorFill} ${idx < activeStepIndex ? summaryStyles.stepConnectorFillComplete : ""} ${connectorShootIndex === idx ? summaryStyles.stepConnectorFillShoot : ""}`
                            }
                          )
                        ] })
                      ] }, s.id);
                    })
                  }
                ),
                step2 !== "target" && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.selectionSlot, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  SimpleServiceOrderSummary,
                  {
                    label: config.label,
                    targetUserIds: useFaction ? factionTargets ?? [] : targetUserId !== null ? [targetUserId] : [],
                    factionId: useFaction ? factionId : null,
                    pricePts
                  }
                ) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.stepViewport, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "div",
                  {
                    className: `${summaryStyles.stepPanel} ${slideDirection === "forward" ? summaryStyles.stepPanelForward : summaryStyles.stepPanelBack}`,
                    children: renderStepContent()
                  },
                  step2
                ) }),
                error2 && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: summaryStyles.errorSlot, children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: summaryStyles.error, children: error2 }) })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${contractStyles.actions} ${summaryStyles.footer}`, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.cancel,
                    onClick: showBack ? handleBack : onCancel,
                    children: showBack ? "Back" : "Cancel"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.confirm,
                    onClick: handlePrimary,
                    disabled: primaryDisabled,
                    children: primaryLabel
                  }
                )
              ] })
            ]
          }
        )
      }
    );
  }
  function SimpleServiceConfirmModal({
    config,
    order,
    balance,
    payoutConversion,
    onConfirm,
    onBack,
    onAddBalance
  }) {
    const targetCount = order.targetUserIds.length;
    const perTargetCost = order.totalCostPts;
    const totalCost = perTargetCost * targetCount;
    const insufficient = totalCost > balance;
    const remainingBalance = balance - totalCost;
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onBack();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: `${contractStyles.overlay} ${contractStyles.overlayElevated} ${contractStyles.overlayElevatedTop}`,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onBack),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-simple-service-confirm-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "h2",
                {
                  id: "tlm-simple-service-confirm-title",
                  className: contractStyles.title,
                  children: [
                    "Confirm ",
                    config.label.toLowerCase()
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("ul", { className: summaryStyles.selectionSummary, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: targetCount > 1 ? "Targets" : "Target" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionValue, children: targetCount === 1 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                    SimpleServiceTargetLink,
                    {
                      targetUserId: order.targetUserIds[0]
                    }
                  ) : `${targetCount} players` })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: summaryStyles.selectionItem, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionLabel, children: "Price each" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.selectionValue, children: formatExtensionPoints(perTargetCost) })
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostGroup, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceLabel, children: "Total cost" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "span",
                    {
                      className: `${summaryStyles.confirmBalanceValue} tlm-payout-hover-scope`,
                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                        PayoutValue,
                        {
                          amount: totalCost,
                          conversion: payoutConversion,
                          label: `${config.label} total cost`
                        }
                      )
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: summaryStyles.confirmCostRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceLabel, children: "Remaining balance" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: summaryStyles.confirmBalanceValue, children: insufficient ? "—" : formatExtensionPoints(remainingBalance) })
                ] })
              ] }),
              insufficient && /* @__PURE__ */ jsxRuntimeExports.jsx(InsufficientBalanceMessage, { onAddBalance }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.cancel, onClick: onBack, children: "Back" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.confirm,
                    onClick: onConfirm,
                    disabled: insufficient,
                    children: "Confirm order"
                  }
                )
              ] })
            ]
          }
        )
      }
    );
  }
  function CancelContractConfirmModal({
    description: description2,
    refundAmount,
    onConfirm,
    onCancel
  }) {
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onCancel();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: contractStyles.overlay,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onCancel),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-cancel-contract-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-cancel-contract-title", className: contractStyles.title, children: "Are you sure?" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.subtitle, children: description2 }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("dl", { className: contractStyles.summaryList, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${contractStyles.summaryRow} ${contractStyles.summaryTotal}`, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "Refund amount" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { children: formatExtensionPoints(refundAmount) })
              ] }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.cancel, onClick: onCancel, children: "Go back" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.confirm, onClick: onConfirm, children: "Confirm cancel" })
              ] })
            ]
          }
        )
      }
    );
  }
  const titleRow = "_titleRow_4kuie_1";
  const copyButton$1 = "_copyButton_4kuie_8";
  const archiveButton = "_archiveButton_4kuie_31";
  const reportDialog = "_reportDialog_4kuie_43";
  const body$2 = "_body_4kuie_54";
  const section$1 = "_section_4kuie_66";
  const heading = "_heading_4kuie_72";
  const row$5 = "_row_4kuie_81";
  const name = "_name_4kuie_95";
  const listerId = "_listerId_4kuie_102";
  const dates = "_dates_4kuie_108";
  const days = "_days_4kuie_118";
  const empty$5 = "_empty_4kuie_128";
  const meta = "_meta_4kuie_134";
  const styles$j = {
    titleRow,
    copyButton: copyButton$1,
    archiveButton,
    reportDialog,
    body: body$2,
    section: section$1,
    heading,
    row: row$5,
    name,
    listerId,
    dates,
    days,
    empty: empty$5,
    meta
  };
  function parseHistoryDate(value) {
    const match = value.match(/^(\d{2})-(\d{2})-(\d{4})$/);
    if (!match) return null;
    const day = Number(match[1]);
    const month = Number(match[2]);
    const year = Number(match[3]);
    const date = new Date(year, month - 1, day);
    return Number.isNaN(date.getTime()) ? null : date;
  }
  function daysPresent(from, to) {
    const fromDate = parseHistoryDate(from);
    if (!fromDate) return null;
    const toDate = to.toLowerCase() === "present" ? /* @__PURE__ */ new Date() : parseHistoryDate(to);
    if (!toDate) return null;
    const days2 = Math.round((toDate.getTime() - fromDate.getTime()) / 864e5);
    return days2 >= 0 ? days2 : null;
  }
  function HistorySection({
    heading: heading2,
    rows
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$j.section, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: styles$j.heading, children: heading2 }),
      rows.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$j.empty, children: "No history found." }) : rows.map((row2, index) => {
        const days2 = row2.from ? daysPresent(row2.from, row2.to) : null;
        return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$j.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$j.name, children: row2.name }),
          row2.from ? /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$j.dates, children: [
            row2.from,
            " → ",
            row2.to,
            days2 != null ? /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$j.days, children: [
              days2,
              "d"
            ] }) : null
          ] }) : null
        ] }, `${row2.name}-${index}`);
      })
    ] });
  }
  function ReferencesReportModal({
    targetUserId,
    report,
    archived = false,
    onClose,
    onArchive,
    onUnarchive
  }) {
    const [copied, setCopied] = reactExports.useState(false);
    reactExports.useEffect(() => {
      const handleKeyDown = (e) => {
        if (e.key === "Escape") onClose();
      };
      window.addEventListener("keydown", handleKeyDown);
      return () => window.removeEventListener("keydown", handleKeyDown);
    }, [onClose]);
    reactExports.useEffect(() => {
      if (!copied) return;
      const timer2 = globalThis.setTimeout(() => setCopied(false), 1500);
      return () => globalThis.clearTimeout(timer2);
    }, [copied]);
    const handleCopyJson = () => {
      var _a2;
      const json = JSON.stringify(report, null, 2);
      void Promise.resolve(
        (_a2 = navigator.clipboard) == null ? void 0 : _a2.writeText(json)
      ).then(() => setCopied(true)).catch(() => {
        try {
          const textarea = document.createElement("textarea");
          textarea.value = json;
          textarea.style.position = "fixed";
          textarea.style.opacity = "0";
          document.body.appendChild(textarea);
          textarea.select();
          document.execCommand("copy");
          document.body.removeChild(textarea);
          setCopied(true);
        } catch {
        }
      });
    };
    const portalTarget = getExtensionShadowMount() ?? document.body;
    return reactDomExports.createPortal(
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: contractStyles.overlay,
          role: "presentation",
          onMouseDown: (e) => overlayMouseDownDismiss(e, onClose),
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: `${contractStyles.dialog} ${styles$j.reportDialog}`,
              role: "dialog",
              "aria-modal": "true",
              "aria-labelledby": "tlm-references-report-title",
              onClick: (e) => e.stopPropagation(),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$j.titleRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "h2",
                    {
                      id: "tlm-references-report-title",
                      className: contractStyles.title,
                      children: "References report"
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      className: styles$j.copyButton,
                      onClick: handleCopyJson,
                      "aria-label": "Copy references report as JSON",
                      children: copied ? "Copied" : "Copy JSON"
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: styles$j.meta, children: [
                  "Target:",
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx(SimpleServiceTargetLink, { targetUserId }),
                  report.targetName ? ` (${report.targetName})` : ""
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$j.body, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    HistorySection,
                    {
                      heading: "Faction service history",
                      rows: report.factionHistory
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    HistorySection,
                    {
                      heading: "Company employment history",
                      rows: report.employmentHistory
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                  archived ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      className: `${contractStyles.actionCompact} ${styles$j.archiveButton}`,
                      onClick: onUnarchive,
                      children: "Unarchive"
                    }
                  ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      className: `${contractStyles.actionCompact} ${styles$j.archiveButton}`,
                      onClick: onArchive,
                      children: "Archive"
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      className: contractStyles.confirm,
                      onClick: onClose,
                      children: "Close"
                    }
                  )
                ] })
              ]
            }
          )
        }
      ),
      portalTarget
    );
  }
  const body$1 = "_body_cdj7n_1";
  const group = "_group_cdj7n_11";
  const groupHeading = "_groupHeading_cdj7n_17";
  const list$4 = "_list_cdj7n_26";
  const row$4 = "_row_cdj7n_32";
  const target = "_target_cdj7n_57";
  const view = "_view_cdj7n_65";
  const empty$4 = "_empty_cdj7n_72";
  const styles$i = {
    body: body$1,
    group,
    groupHeading,
    list: list$4,
    row: row$4,
    target,
    view,
    empty: empty$4
  };
  function ArchiveSection({
    heading: heading2,
    rows
  }) {
    if (rows.length === 0) return null;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$i.group, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: styles$i.groupHeading, children: heading2 }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$i.list, children: rows.map((row2) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          className: styles$i.row,
          onClick: row2.onView,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$i.target, children: row2.label }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$i.view, "aria-hidden": true, children: "View" })
          ]
        },
        row2.key
      )) })
    ] });
  }
  function ArchivedReferencesModal({
    references,
    bountyReveals,
    onViewReferences,
    onViewBountyReveal,
    onClose
  }) {
    reactExports.useEffect(() => {
      const handleKeyDown = (e) => {
        if (e.key === "Escape") onClose();
      };
      window.addEventListener("keydown", handleKeyDown);
      return () => window.removeEventListener("keydown", handleKeyDown);
    }, [onClose]);
    const portalTarget = getExtensionShadowMount() ?? document.body;
    const referenceRows = references.map((order) => {
      var _a2;
      return {
        key: order.id,
        label: ((_a2 = order.report) == null ? void 0 : _a2.targetName) ? order.report.targetName : `ID ${order.targetUserId.toLocaleString("en-US")}`,
        onView: () => onViewReferences(order)
      };
    });
    const bountyRevealRows = bountyReveals.map((order) => {
      var _a2;
      return {
        key: order.id,
        label: ((_a2 = order.report) == null ? void 0 : _a2.targetName) ? order.report.targetName : `ID ${order.targetUserId.toLocaleString("en-US")}`,
        onView: () => onViewBountyReveal(order)
      };
    });
    const isEmpty = referenceRows.length === 0 && bountyRevealRows.length === 0;
    return reactDomExports.createPortal(
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: contractStyles.overlay,
          role: "presentation",
          onMouseDown: (e) => overlayMouseDownDismiss(e, onClose),
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: contractStyles.dialog,
              role: "dialog",
              "aria-modal": "true",
              "aria-labelledby": "tlm-archive-title",
              onClick: (e) => e.stopPropagation(),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-archive-title", className: contractStyles.title, children: "Archive" }),
                isEmpty ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$i.empty, children: "No archived reports yet." }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$i.body, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ArchiveSection, { heading: "References", rows: referenceRows }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(ArchiveSection, { heading: "Bounty Reveal", rows: bountyRevealRows })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: contractStyles.actions, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.confirm,
                    onClick: onClose,
                    children: "Close"
                  }
                ) })
              ]
            }
          )
        }
      ),
      portalTarget
    );
  }
  function formatReward(reward) {
    if (!Number.isFinite(reward) || reward <= 0) return "";
    return `$${reward.toLocaleString("en-US")}`;
  }
  function BountyRevealReportModal({
    targetUserId,
    report,
    archived = false,
    onClose,
    onArchive,
    onUnarchive
  }) {
    const [copied, setCopied] = reactExports.useState(false);
    reactExports.useEffect(() => {
      const handleKeyDown = (e) => {
        if (e.key === "Escape") onClose();
      };
      window.addEventListener("keydown", handleKeyDown);
      return () => window.removeEventListener("keydown", handleKeyDown);
    }, [onClose]);
    reactExports.useEffect(() => {
      if (!copied) return;
      const timer2 = globalThis.setTimeout(() => setCopied(false), 1500);
      return () => globalThis.clearTimeout(timer2);
    }, [copied]);
    const handleCopyJson = () => {
      var _a2;
      const json = JSON.stringify(report, null, 2);
      void Promise.resolve((_a2 = navigator.clipboard) == null ? void 0 : _a2.writeText(json)).then(() => setCopied(true)).catch(() => {
        try {
          const textarea = document.createElement("textarea");
          textarea.value = json;
          textarea.style.position = "fixed";
          textarea.style.opacity = "0";
          document.body.appendChild(textarea);
          textarea.select();
          document.execCommand("copy");
          document.body.removeChild(textarea);
          setCopied(true);
        } catch {
        }
      });
    };
    const portalTarget = getExtensionShadowMount() ?? document.body;
    return reactDomExports.createPortal(
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: contractStyles.overlay,
          role: "presentation",
          onMouseDown: (e) => overlayMouseDownDismiss(e, onClose),
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: `${contractStyles.dialog} ${styles$j.reportDialog}`,
              role: "dialog",
              "aria-modal": "true",
              "aria-labelledby": "tlm-bounty-reveal-report-title",
              onClick: (e) => e.stopPropagation(),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$j.titleRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "h2",
                    {
                      id: "tlm-bounty-reveal-report-title",
                      className: contractStyles.title,
                      children: "Bounty reveal report"
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      className: styles$j.copyButton,
                      onClick: handleCopyJson,
                      "aria-label": "Copy bounty reveal report as JSON",
                      children: copied ? "Copied" : "Copy JSON"
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: styles$j.meta, children: [
                  "Target: ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx(SimpleServiceTargetLink, { targetUserId }),
                  report.targetName ? ` (${report.targetName})` : ""
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$j.body, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$j.section, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("h3", { className: styles$j.heading, children: [
                    "Bounty listers (",
                    report.bounties.length,
                    ")"
                  ] }),
                  report.bounties.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$j.empty, children: "No active bounties found." }) : report.bounties.map((row2, index) => /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "div",
                    {
                      className: styles$j.row,
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$j.name, children: [
                          row2.name,
                          row2.listerId != null ? /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$j.listerId, children: [
                            " [",
                            row2.listerId,
                            "]"
                          ] }) : null
                        ] }),
                        formatReward(row2.reward) ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$j.dates, children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$j.days, children: formatReward(row2.reward) }) }) : null
                      ]
                    },
                    `${row2.listerId ?? row2.name}-${index}`
                  ))
                ] }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                  archived ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      className: `${contractStyles.actionCompact} ${styles$j.archiveButton}`,
                      onClick: onUnarchive,
                      children: "Unarchive"
                    }
                  ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      className: `${contractStyles.actionCompact} ${styles$j.archiveButton}`,
                      onClick: onArchive,
                      children: "Archive"
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      className: contractStyles.confirm,
                      onClick: onClose,
                      children: "Close"
                    }
                  )
                ] })
              ]
            }
          )
        }
      ),
      portalTarget
    );
  }
  function CancelBountyOrderModal({
    order,
    refundAmount,
    payoutConversion,
    onConfirm,
    onCancel
  }) {
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onCancel();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: contractStyles.overlay,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onCancel),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-cancel-bounty-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-cancel-bounty-title", className: contractStyles.title, children: "Are you sure?" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.subtitle, children: "This will cancel your open bounty order and return escrowed funds for bounties not yet placed." }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("dl", { className: contractStyles.summaryList, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.summaryRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "Quantity remaining" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("dd", { children: [
                    order.quantityRemaining.toLocaleString("en-US"),
                    "/",
                    order.quantity.toLocaleString("en-US")
                  ] })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${contractStyles.summaryRow} ${contractStyles.summaryTotal}`, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "Refund amount" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { className: "tlm-payout-hover-scope", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    PayoutValue,
                    {
                      amount: refundAmount,
                      conversion: payoutConversion,
                      label: "Bounty order refund amount"
                    }
                  ) })
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.cancel, onClick: onCancel, children: "Go back" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.confirm, onClick: onConfirm, children: "Confirm cancel" })
              ] })
            ]
          }
        )
      }
    );
  }
  function getBountyOrderRefundAmount(order) {
    return order.escrowedTotal * (order.quantityRemaining / order.quantity);
  }
  function CancelBuyerOrderModal({
    refundAmount,
    onConfirm,
    onCancel
  }) {
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onCancel();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: contractStyles.overlay,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onCancel),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-cancel-buyer-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-cancel-buyer-title", className: contractStyles.title, children: "Are you sure?" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.subtitle, children: "This will cancel your open buy order and return escrowed funds for losses not yet filled." }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("dl", { className: contractStyles.summaryList, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${contractStyles.summaryRow} ${contractStyles.summaryTotal}`, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "Refund amount" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { children: formatExtensionPoints(refundAmount) })
              ] }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.cancel, onClick: onCancel, children: "Go back" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.confirm, onClick: onConfirm, children: "Confirm cancel" })
              ] })
            ]
          }
        )
      }
    );
  }
  const dialog = "_dialog_1azzx_1";
  const progressSection = "_progressSection_1azzx_9";
  const progressTrack = "_progressTrack_1azzx_15";
  const progressFill = "_progressFill_1azzx_25";
  const progressBarLabel = "_progressBarLabel_1azzx_36";
  const contributorsSection = "_contributorsSection_1azzx_53";
  const contributorsHeader = "_contributorsHeader_1azzx_59";
  const sortButton = "_sortButton_1azzx_66";
  const sortButtonActive = "_sortButtonActive_1azzx_88";
  const sortButtonRight = "_sortButtonRight_1azzx_92";
  const sortIndicator = "_sortIndicator_1azzx_96";
  const contributorsList = "_contributorsList_1azzx_101";
  const contributorRow = "_contributorRow_1azzx_112";
  const sellerLink$2 = "_sellerLink_1azzx_123";
  const attacksValue = "_attacksValue_1azzx_137";
  const empty$3 = "_empty_1azzx_146";
  const styles$h = {
    dialog,
    progressSection,
    progressTrack,
    progressFill,
    progressBarLabel,
    contributorsSection,
    contributorsHeader,
    sortButton,
    sortButtonActive,
    sortButtonRight,
    sortIndicator,
    contributorsList,
    contributorRow,
    sellerLink: sellerLink$2,
    attacksValue,
    empty: empty$3
  };
  function aggregateContributors(contributors) {
    const bySeller = /* @__PURE__ */ new Map();
    for (const contributor of contributors) {
      bySeller.set(
        contributor.sellerId,
        (bySeller.get(contributor.sellerId) ?? 0) + contributor.attacksVerified
      );
    }
    return [...bySeller.entries()].map(([sellerId, attacksVerified]) => ({
      sellerId,
      attacksVerified
    }));
  }
  function sortContributors(contributors, sortKey, sortDir) {
    const sorted = [...contributors];
    const factor = sortDir === "asc" ? 1 : -1;
    sorted.sort((a, b) => {
      if (sortKey === "attacks") {
        const diff2 = a.attacksVerified - b.attacksVerified;
        if (diff2 !== 0) return diff2 * factor;
        return a.sellerId - b.sellerId;
      }
      const aId = formatTornUserId(a.sellerId);
      const bId = formatTornUserId(b.sellerId);
      const diff = aId.localeCompare(bId, void 0, { numeric: true });
      if (diff !== 0) return diff * factor;
      return b.attacksVerified - a.attacksVerified;
    });
    return sorted;
  }
  function BuyerOrderProgressModal({
    order,
    onClose,
    onTogglePause
  }) {
    const [sortKey, setSortKey] = reactExports.useState("attacks");
    const [sortDir, setSortDir] = reactExports.useState("desc");
    const [progressHovered, setProgressHovered] = reactExports.useState(false);
    reactExports.useEffect(() => {
      const handleKeyDown = (e) => {
        if (e.key === "Escape") onClose();
      };
      window.addEventListener("keydown", handleKeyDown);
      return () => window.removeEventListener("keydown", handleKeyDown);
    }, [onClose]);
    const orderLabel = CONTRACT_TYPE_LABELS[order.contractType];
    const verified = buyerOrderVerifiedCount(order);
    const percent2 = buyerOrderProgressPercent(order);
    const fillWidth = Math.max(percent2, percent2 > 0 ? 3 : 0);
    const attacksCompletedLabel = `${verified.toLocaleString("en-US")} / ${order.quantity.toLocaleString("en-US")} attacks completed`;
    const aggregatedContributors = reactExports.useMemo(
      () => aggregateContributors(order.contributors),
      [order.contributors]
    );
    const sortedContributors = reactExports.useMemo(
      () => sortContributors(aggregatedContributors, sortKey, sortDir),
      [aggregatedContributors, sortKey, sortDir]
    );
    const toggleSort = (key) => {
      if (sortKey === key) {
        setSortDir((prev) => prev === "asc" ? "desc" : "asc");
        return;
      }
      setSortKey(key);
      setSortDir(key === "attacks" ? "desc" : "asc");
    };
    const sortIndicator2 = (key) => {
      if (sortKey !== key) return null;
      return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$h.sortIndicator, "aria-hidden": true, children: sortDir === "asc" ? "▲" : "▼" });
    };
    const portalTarget = getExtensionShadowMount() ?? document.body;
    return reactDomExports.createPortal(
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: contractStyles.overlay,
          role: "presentation",
          onMouseDown: (e) => overlayMouseDownDismiss(e, onClose),
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: `${contractStyles.dialog} ${styles$h.dialog}`,
              role: "dialog",
              "aria-modal": "true",
              "aria-labelledby": "tlm-buyer-progress-title",
              onClick: (e) => e.stopPropagation(),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("h2", { id: "tlm-buyer-progress-title", className: contractStyles.title, children: [
                  orderLabel,
                  " contract — progress"
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$h.progressSection, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "div",
                  {
                    className: styles$h.progressTrack,
                    role: "progressbar",
                    "aria-valuenow": percent2,
                    "aria-valuemin": 0,
                    "aria-valuemax": 100,
                    "aria-label": `${orderLabel} contract progress — ${attacksCompletedLabel}`,
                    onMouseEnter: () => setProgressHovered(true),
                    onMouseLeave: () => setProgressHovered(false),
                    onFocus: () => setProgressHovered(true),
                    onBlur: () => setProgressHovered(false),
                    tabIndex: 0,
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "div",
                        {
                          className: styles$h.progressFill,
                          style: { width: `${fillWidth}%` }
                        }
                      ),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$h.progressBarLabel, children: progressHovered ? attacksCompletedLabel : `${percent2}%` })
                    ]
                  }
                ) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$h.contributorsSection, children: aggregatedContributors.length > 0 ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$h.contributorsHeader, children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      "button",
                      {
                        type: "button",
                        className: `${styles$h.sortButton} ${sortKey === "tornId" ? styles$h.sortButtonActive : ""}`,
                        onClick: () => toggleSort("tornId"),
                        children: [
                          "Torn ID",
                          sortIndicator2("tornId")
                        ]
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      "button",
                      {
                        type: "button",
                        className: `${styles$h.sortButton} ${styles$h.sortButtonRight} ${sortKey === "attacks" ? styles$h.sortButtonActive : ""}`,
                        onClick: () => toggleSort("attacks"),
                        children: [
                          "Attacks",
                          sortIndicator2("attacks")
                        ]
                      }
                    )
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: styles$h.contributorsList, children: sortedContributors.map((contributor) => /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: styles$h.contributorRow, children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "a",
                      {
                        className: styles$h.sellerLink,
                        href: getSellerProfileUrl(contributor.sellerId),
                        target: "_blank",
                        rel: "noopener noreferrer",
                        children: formatTornUserId(contributor.sellerId)
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$h.attacksValue, children: contributor.attacksVerified.toLocaleString("en-US") })
                  ] }, contributor.sellerId)) })
                ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$h.empty, children: "No verified attacks yet." }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actionsSplit, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "button",
                    {
                      type: "button",
                      className: `${contractStyles.actionCompact} ${contractStyles.pauseButton}`,
                      onClick: onTogglePause,
                      "aria-label": order.isPaused ? "Resume contract and release reserved slots" : "Pause contract and reserve all empty slots",
                      children: [
                        order.isPaused ? /* @__PURE__ */ jsxRuntimeExports.jsx(CirclePlay, { size: 16, strokeWidth: 2, "aria-hidden": true }) : /* @__PURE__ */ jsxRuntimeExports.jsx(CirclePause, { size: 16, strokeWidth: 2, "aria-hidden": true }),
                        order.isPaused ? "Resume" : "Pause"
                      ]
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      className: contractStyles.confirm,
                      onClick: onClose,
                      children: "Close"
                    }
                  )
                ] })
              ]
            }
          )
        }
      ),
      portalTarget
    );
  }
  function CancelRedeemingRequestModal({
    refundAmount,
    onConfirm,
    onCancel
  }) {
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onCancel();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: contractStyles.overlay,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onCancel),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-cancel-redeem-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-cancel-redeem-title", className: contractStyles.title, children: "Are you sure?" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.subtitle, children: "This will cancel your withdrawal request and return the escrowed amount to your balance." }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("dl", { className: contractStyles.summaryList, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${contractStyles.summaryRow} ${contractStyles.summaryTotal}`, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "Refund amount" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { children: formatExtensionPoints(refundAmount) })
              ] }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.cancel, onClick: onCancel, children: "Go back" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.confirm, onClick: onConfirm, children: "Confirm cancel" })
              ] })
            ]
          }
        )
      }
    );
  }
  function RequesterLink({ requesterId }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "a",
      {
        className: contractStyles.profileLink,
        href: getRequesterProfileUrl(requesterId),
        target: "_blank",
        rel: "noopener noreferrer",
        children: formatRequesterId(requesterId)
      }
    );
  }
  function parseXanaxQuantity(raw, max) {
    const value = evaluateNumericInput(raw);
    if (value === null || !Number.isInteger(value) || value < 1 || value > max) return null;
    return value;
  }
  function RedeemingFulfillModal({
    listing,
    onConfirm,
    onCancel,
    payoutConversion
  }) {
    const maxQuantity = listing.quantity;
    const inputRef = reactExports.useRef(null);
    const [quantityInput, setQuantityInput] = reactExports.useState("1");
    const [error2, setError] = reactExports.useState(null);
    const quantity2 = reactExports.useMemo(
      () => parseXanaxQuantity(quantityInput, maxQuantity),
      [quantityInput, maxQuantity]
    );
    const payout2 = quantity2 !== null ? getRedeemingPayAmount(quantity2) : null;
    reactExports.useEffect(() => {
      var _a2, _b;
      (_a2 = inputRef.current) == null ? void 0 : _a2.focus();
      (_b = inputRef.current) == null ? void 0 : _b.select();
    }, []);
    const handleConfirm = reactExports.useCallback(() => {
      if (quantity2 === null) {
        setError(`Enter a whole number from 1 to ${maxQuantity.toLocaleString("en-US")}.`);
        return;
      }
      onConfirm(quantity2, listing);
    }, [quantity2, listing, maxQuantity, onConfirm]);
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onCancel();
      } else if (e.key === "Enter") {
        e.preventDefault();
        handleConfirm();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: contractStyles.overlay,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onCancel),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-redeem-fulfill-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-redeem-fulfill-title", className: contractStyles.title, children: "Fulfill request" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: contractStyles.label, htmlFor: "tlm-redeem-xanax-quantity", children: [
                "How much Xanax would you like to send to",
                " ",
                /* @__PURE__ */ jsxRuntimeExports.jsx(RequesterLink, { requesterId: listing.requesterId }),
                "?"
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                PtsAmountInput,
                {
                  id: "tlm-redeem-xanax-quantity",
                  inputRef,
                  value: quantityInput,
                  onChange: (next) => {
                    setQuantityInput(next);
                    setError(null);
                  },
                  max: maxQuantity,
                  referenceMax: maxQuantity,
                  symbolLabel: "MAX",
                  inputMode: "numeric",
                  hasError: Boolean(error2)
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.hintRow, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: contractStyles.hint, children: [
                  "Enter a value between 1 and ",
                  maxQuantity.toLocaleString("en-US"),
                  "."
                ] }),
                payout2 !== null && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${contractStyles.payout} tlm-payout-hover-scope`, children: [
                  "Pay:",
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    PayoutValue,
                    {
                      amount: payout2,
                      conversion: payoutConversion,
                      label: "Withdrawal contract payout"
                    }
                  )
                ] })
              ] }),
              error2 && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.error, children: error2 }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: contractStyles.notice, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { style: { margin: 0 }, children: [
                "You have ",
                /* @__PURE__ */ jsxRuntimeExports.jsxs("strong", { children: [
                  REDEEMING_FULFILL_MINUTES,
                  " minutes"
                ] }),
                " to fulfill this request."
              ] }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: contractStyles.noticeWarning, children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { style: { margin: 0 }, children: "Payment is contingent on fulfilling the specified quantity." }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.cancel, onClick: onCancel, children: "Cancel" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.confirm, onClick: handleConfirm, children: "Confirm" })
              ] })
            ]
          }
        )
      }
    );
  }
  function sanitizeSlotQuantityInput(raw, max) {
    const digits = raw.replace(/\D/g, "");
    if (!digits) return "";
    const value = Math.min(Number(digits), max);
    return String(value);
  }
  function parseSlotQuantity(raw, max) {
    const trimmed = raw.trim();
    if (!/^\d+$/.test(trimmed)) return null;
    const value = Number(trimmed);
    if (value < 1 || value > max) return null;
    return value;
  }
  function BountyFulfillModal({
    order,
    onConfirm,
    onCancel
  }) {
    const maxQuantity = Math.min(BOUNTY_FULFILL_MAX, order.quantityRemaining);
    const inputRef = reactExports.useRef(null);
    const [quantityInput, setQuantityInput] = reactExports.useState("1");
    const [error2, setError] = reactExports.useState(null);
    const quantity2 = reactExports.useMemo(
      () => parseSlotQuantity(quantityInput, maxQuantity),
      [quantityInput, maxQuantity]
    );
    const cashOnHandTorn = quantity2 !== null ? computeBountyListingCostTorn(quantity2, order.bountyValueTorn) : null;
    reactExports.useEffect(() => {
      var _a2, _b;
      (_a2 = inputRef.current) == null ? void 0 : _a2.focus();
      (_b = inputRef.current) == null ? void 0 : _b.select();
    }, []);
    const handleConfirm = reactExports.useCallback(() => {
      if (quantity2 === null) {
        setError(
          `Enter a whole number from 1 to ${maxQuantity.toLocaleString("en-US")}.`
        );
        return;
      }
      onConfirm(quantity2, order);
    }, [quantity2, order, maxQuantity, onConfirm]);
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.preventDefault();
        onCancel();
      } else if (e.key === "Enter") {
        e.preventDefault();
        handleConfirm();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: contractStyles.overlay,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onCancel),
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-bounty-fulfill-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-bounty-fulfill-title", className: contractStyles.title, children: "Sell Bounty Slots" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: contractStyles.label, htmlFor: "tlm-bounty-slot-quantity", children: "How many bounty slots would you like to sell?" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "input",
                {
                  ref: inputRef,
                  id: "tlm-bounty-slot-quantity",
                  className: `${contractStyles.input} ${error2 ? contractStyles.inputError : ""}`,
                  type: "text",
                  inputMode: "numeric",
                  autoComplete: "off",
                  value: quantityInput,
                  onChange: (e) => {
                    setQuantityInput(
                      sanitizeSlotQuantityInput(e.target.value, maxQuantity)
                    );
                    setError(null);
                  }
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.hintBlock, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: contractStyles.hint, children: [
                  "Enter a value between 1 and ",
                  BOUNTY_FULFILL_MAX,
                  "."
                ] }),
                cashOnHandTorn !== null && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: contractStyles.payout, children: [
                  "Torn cash on hand required:",
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx("strong", { children: formatMoney(cashOnHandTorn) })
                ] })
              ] }),
              error2 && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.error, children: error2 }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.cancel, onClick: onCancel, children: "Cancel" }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: contractStyles.confirm, onClick: handleConfirm, children: "Confirm" })
              ] })
            ]
          }
        )
      }
    );
  }
  const STORAGE_KEY$9 = "withdraw_button_intro_seen";
  async function hasSeenWithdrawButtonTutorial() {
    try {
      return await getPlatformRuntime().storage.get(STORAGE_KEY$9) === true;
    } catch {
      return false;
    }
  }
  async function markWithdrawButtonTutorialSeen() {
    try {
      await getPlatformRuntime().storage.set(STORAGE_KEY$9, true);
    } catch {
    }
  }
  const STORAGE_KEY$8 = "points_intro_seen";
  async function hasSeenPointsIntro() {
    try {
      return await getPlatformRuntime().storage.get(STORAGE_KEY$8) === true;
    } catch {
      return false;
    }
  }
  async function markPointsIntroSeen() {
    try {
      await getPlatformRuntime().storage.set(STORAGE_KEY$8, true);
    } catch {
    }
  }
  const DEPOSIT_PROFILE_URL = `https://www.torn.com/profiles.php?XID=${DEPOSIT_PLAYER_XID}`;
  function BalanceModal({
    balance,
    payoutConversion,
    onClose,
    onWithdraw,
    onBeforeWithdraw,
    initialView = "deposit",
    firstContractCompleted = false
  }) {
    const [view2, setView] = reactExports.useState(initialView);
    const [millionsInput, setMillionsInput] = reactExports.useState("");
    const [withdrawError, setWithdrawError] = reactExports.useState(null);
    const [infoOpen, setInfoOpen] = reactExports.useState(false);
    const [introVisible, setIntroVisible] = reactExports.useState(false);
    const [withdrawSpotlightVisible, setWithdrawSpotlightVisible] = reactExports.useState(false);
    const [withdrawSpotlightOpacity, setWithdrawSpotlightOpacity] = reactExports.useState(0);
    const withdrawTabRef = reactExports.useRef(null);
    const extensionMount = getExtensionShadowMount();
    reactExports.useEffect(() => {
      let cancelled = false;
      void hasSeenPointsIntro().then((seen) => {
        if (cancelled || seen) return;
        setIntroVisible(true);
      });
      return () => {
        cancelled = true;
      };
    }, []);
    const dismissIntro = () => {
      if (!introVisible) return;
      setIntroVisible(false);
      void markPointsIntroSeen();
    };
    reactExports.useEffect(() => {
      if (!firstContractCompleted) return;
      let cancelled = false;
      void hasSeenWithdrawButtonTutorial().then((seen) => {
        if (cancelled || seen) return;
        setWithdrawSpotlightVisible(true);
      });
      return () => {
        cancelled = true;
      };
    }, [firstContractCompleted]);
    reactExports.useEffect(() => {
      if (!withdrawSpotlightVisible || view2 !== "deposit") {
        setWithdrawSpotlightOpacity(0);
        return;
      }
      const id2 = requestAnimationFrame(() => {
        requestAnimationFrame(() => setWithdrawSpotlightOpacity(1));
      });
      return () => cancelAnimationFrame(id2);
    }, [withdrawSpotlightVisible, view2]);
    const dismissWithdrawSpotlight = () => {
      if (!withdrawSpotlightVisible) return;
      setWithdrawSpotlightVisible(false);
      void markWithdrawButtonTutorialSeen();
    };
    const handleKeyDown = (e) => {
      if (e.key !== "Escape") return;
      e.preventDefault();
      if (infoOpen) {
        setInfoOpen(false);
        return;
      }
      onClose();
    };
    const goToWithdraw = () => {
      if (onBeforeWithdraw && !onBeforeWithdraw()) return;
      dismissWithdrawSpotlight();
      setView("withdraw");
      setWithdrawError(null);
    };
    const goToDeposit = () => {
      setView("deposit");
      setWithdrawError(null);
    };
    const xanaxCount = millionsInput ? Number(millionsInput.replace(/,/g, "")) : null;
    const maxAffordableXanax = Math.floor(balance / getWithdrawTotalDebit(1));
    const sanitizeWithdrawInput = (raw) => {
      const digits = raw.replace(/[^\d]/g, "");
      if (!digits) return "";
      return Number(digits).toLocaleString("en-US");
    };
    const totalDebit = xanaxCount !== null && Number.isInteger(xanaxCount) && xanaxCount > 0 ? getWithdrawTotalDebit(xanaxCount) : null;
    const remainingBalance = totalDebit !== null ? balance - totalDebit : null;
    const canWithdraw = totalDebit !== null && totalDebit <= balance && xanaxCount !== null;
    const withdrawTornHint = reactExports.useMemo(() => {
      var _a2;
      const averagePrice = (_a2 = payoutConversion.price) == null ? void 0 : _a2.averagePrice;
      if (xanaxCount === null || !Number.isInteger(xanaxCount) || xanaxCount < 1 || averagePrice == null) {
        return null;
      }
      const ptsWithdrawn = getWithdrawAmount(xanaxCount);
      const tornValue = convertScriptDollarsToTornDollars(
        ptsWithdrawn,
        averagePrice
      );
      return `(${formatMoney(tornValue)})`;
    }, [payoutConversion.price, xanaxCount]);
    const handleWithdrawSubmit = () => {
      if (xanaxCount === null || !Number.isInteger(xanaxCount) || xanaxCount < 1) {
        setWithdrawError("Enter how many Xanax you would like to withdraw.");
        return;
      }
      if (totalDebit === null || totalDebit > balance) {
        setWithdrawError("Insufficient balance for this withdrawal and fee.");
        return;
      }
      onWithdraw(xanaxCount);
      onClose();
    };
    const balanceSummary = /* @__PURE__ */ jsxRuntimeExports.jsx("dl", { className: contractStyles.summaryList, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.summaryRow, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "Your balance" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("dd", { children: [
        formatExtensionPoints(balance),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: contractStyles.summarySub, children: [
          "≈ ",
          formatPointsAsXanax(balance)
        ] })
      ] })
    ] }) });
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PanelButtonTutorial,
        {
          visible: withdrawSpotlightVisible && view2 === "deposit",
          opacity: withdrawSpotlightOpacity,
          fadeMs: 300,
          targetRef: withdrawTabRef,
          onTransitionEnd: () => {
          },
          portalTarget: extensionMount,
          layerZIndex: API_KEY_SPOTLIGHT_Z
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: `${contractStyles.overlay} ${contractStyles.overlayElevated}`,
          role: "presentation",
          onMouseDown: (e) => overlayMouseDownDismiss(e, onClose),
          onKeyDown: handleKeyDown,
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: contractStyles.dialog,
              role: "dialog",
              "aria-modal": "true",
              "aria-labelledby": "tlm-wallet-title",
              onClick: (e) => e.stopPropagation(),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.walletHeader, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-wallet-title", className: contractStyles.title, children: "Wallet" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      className: contractStyles.infoButton,
                      "aria-label": "How points work",
                      "aria-expanded": infoOpen,
                      onClick: () => setInfoOpen((open) => !open),
                      children: "?"
                    }
                  ),
                  infoOpen && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.infoPopover, role: "note", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("strong", { children: "How points work." }),
                    " Points (PTS) are how you trade on The Panel. ",
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("strong", { children: [
                      "1 ",
                      DEPOSIT_ITEM_NAME,
                      " = 1,000,000 PTS."
                    ] }),
                    " Deposit ",
                    DEPOSIT_ITEM_NAME,
                    " to top up points you can spend, or withdraw to turn points back into",
                    " ",
                    DEPOSIT_ITEM_NAME,
                    "."
                  ] })
                ] }),
                introVisible && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.introBanner, role: "note", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: contractStyles.introText, children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("strong", { children: "New here?" }),
                    " Your balance is in points. 1",
                    " ",
                    DEPOSIT_ITEM_NAME,
                    " = 1,000,000 PTS — so what you earn selling cashes out as ",
                    DEPOSIT_ITEM_NAME,
                    " from the Withdraw tab."
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      className: contractStyles.introDismiss,
                      "aria-label": "Dismiss",
                      onClick: dismissIntro,
                      children: "✕"
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.tabs, role: "tablist", "aria-label": "Wallet actions", children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      role: "tab",
                      "aria-selected": view2 === "deposit",
                      className: `${contractStyles.tab} ${view2 === "deposit" ? contractStyles.tabActive : ""}`,
                      onClick: goToDeposit,
                      children: "Deposit"
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      ref: withdrawTabRef,
                      type: "button",
                      role: "tab",
                      "aria-selected": view2 === "withdraw",
                      className: `${contractStyles.tab} ${view2 === "withdraw" ? contractStyles.tabActive : ""}`,
                      onClick: goToWithdraw,
                      children: "Withdraw"
                    }
                  )
                ] }),
                view2 === "deposit" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: contractStyles.subtitle, children: [
                    "Add points to spend as a buyer. Send ",
                    DEPOSIT_ITEM_NAME,
                    " to",
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      "a",
                      {
                        className: contractStyles.profileLink,
                        href: DEPOSIT_PROFILE_URL,
                        target: "_blank",
                        rel: "noopener noreferrer",
                        children: [
                          DEPOSIT_PLAYER_NAME,
                          " [",
                          DEPOSIT_PLAYER_XID,
                          "]"
                        ]
                      }
                    ),
                    "."
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: contractStyles.notice, children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("strong", { children: [
                      "1 ",
                      DEPOSIT_ITEM_NAME,
                      " =",
                      " ",
                      formatExtensionPoints(DEPOSIT_AMOUNT_PER_ITEM),
                      "."
                    ] }),
                    " ",
                    "Bulk sends are supported. Balance can take up to 60 seconds to update."
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: contractStyles.trustNote, children: [
                    DEPOSIT_PLAYER_NAME,
                    " is The Panel's deposit account — points are credited to you automatically once your ",
                    DEPOSIT_ITEM_NAME,
                    " ",
                    "arrives."
                  ] }),
                  balance > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: contractStyles.depositRedirect, children: [
                    "Just here to cash out?",
                    " ",
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        className: contractStyles.linkButton,
                        onClick: goToWithdraw,
                        children: "Switch to Withdraw"
                      }
                    ),
                    " ",
                    "— you don't need to deposit."
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: contractStyles.actionsSplit, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      className: `${contractStyles.actionCompact} ${contractStyles.confirmCompact} ${contractStyles.gotItButton}`,
                      onClick: onClose,
                      children: "Got it"
                    }
                  ) })
                ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: contractStyles.subtitle, children: [
                    "Convert your points back into ",
                    DEPOSIT_ITEM_NAME,
                    ". A 5% fee applies."
                  ] }),
                  balanceSummary,
                  /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "label",
                    {
                      className: contractStyles.label,
                      htmlFor: "tlm-withdraw-millions",
                      style: { marginTop: 16 },
                      children: [
                        DEPOSIT_ITEM_NAME,
                        " to withdraw"
                      ]
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    PtsAmountInput,
                    {
                      id: "tlm-withdraw-millions",
                      value: millionsInput,
                      onChange: (next) => {
                        setMillionsInput(next);
                        setWithdrawError(null);
                      },
                      max: Number.MAX_SAFE_INTEGER,
                      referenceMax: maxAffordableXanax || 1,
                      sanitize: sanitizeWithdrawInput,
                      symbolLabel: DEPOSIT_ITEM_NAME,
                      inputMode: "numeric",
                      placeholder: "e.g. 5",
                      ariaLabel: "Xanax to withdraw",
                      hasError: Boolean(withdrawError && millionsInput),
                      postfix: withdrawTornHint
                    }
                  ),
                  totalDebit !== null && /* @__PURE__ */ jsxRuntimeExports.jsxs("dl", { className: contractStyles.summaryList, children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${contractStyles.summaryRow} ${contractStyles.summaryTotal}`, children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "Cost (incl. 5% fee)" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { children: formatExtensionPoints(totalDebit) })
                    ] }),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      "div",
                      {
                        className: `${contractStyles.summaryRow} ${remainingBalance !== null && remainingBalance < 0 ? contractStyles.summaryNegative : ""}`,
                        children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "Remaining balance" }),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("dd", { children: [
                            remainingBalance !== null ? formatExtensionPoints(remainingBalance) : "—",
                            remainingBalance !== null && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: contractStyles.summarySub, children: [
                              "≈ ",
                              formatPointsAsXanax(remainingBalance)
                            ] })
                          ] })
                        ]
                      }
                    )
                  ] }),
                  withdrawError && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.error, children: withdrawError }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.noticeWarning, children: "Withdrawals may take up to 8 hours to process." }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actionsSplit, children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        className: `${contractStyles.actionCompact} ${contractStyles.actionSecondary}`,
                        onClick: onClose,
                        children: "Close"
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        className: `${contractStyles.actionCompact} ${contractStyles.confirmCompact}`,
                        onClick: handleWithdrawSubmit,
                        disabled: !canWithdraw,
                        children: "Confirm"
                      }
                    )
                  ] })
                ] })
              ]
            }
          )
        }
      )
    ] });
  }
  const HOLD_MS = 5e3;
  function DeleteAccountModal({
    onConfirm,
    onCancel,
    deleting = false,
    error: error2 = null
  }) {
    const [acknowledged, setAcknowledged] = reactExports.useState(false);
    const [holdProgress, setHoldProgress] = reactExports.useState(0);
    const holdStartRef = reactExports.useRef(null);
    const holdFrameRef = reactExports.useRef(null);
    const confirmedRef = reactExports.useRef(false);
    const stopHold = reactExports.useCallback(() => {
      holdStartRef.current = null;
      if (holdFrameRef.current !== null) {
        cancelAnimationFrame(holdFrameRef.current);
        holdFrameRef.current = null;
      }
      setHoldProgress(0);
    }, []);
    const completeHold = reactExports.useCallback(() => {
      if (confirmedRef.current || deleting) return;
      confirmedRef.current = true;
      stopHold();
      void Promise.resolve(onConfirm());
    }, [deleting, onConfirm, stopHold]);
    const tickHold = reactExports.useCallback(() => {
      const start = holdStartRef.current;
      if (start === null) return;
      const elapsed = Date.now() - start;
      const progress2 = Math.min(1, elapsed / HOLD_MS);
      setHoldProgress(progress2);
      if (progress2 >= 1) {
        completeHold();
        return;
      }
      holdFrameRef.current = requestAnimationFrame(tickHold);
    }, [completeHold]);
    const startHold = reactExports.useCallback(() => {
      if (!acknowledged || deleting || confirmedRef.current) return;
      holdStartRef.current = Date.now();
      holdFrameRef.current = requestAnimationFrame(tickHold);
    }, [acknowledged, deleting, tickHold]);
    reactExports.useEffect(() => {
      return () => {
        if (holdFrameRef.current !== null) {
          cancelAnimationFrame(holdFrameRef.current);
        }
      };
    }, []);
    const handleKeyDown = (e) => {
      if (e.key === "Escape" && !deleting) {
        e.preventDefault();
        onCancel();
      }
    };
    const canHold = acknowledged && !deleting && !confirmedRef.current;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: contractStyles.overlay,
        role: "presentation",
        onMouseDown: (e) => {
          if (!deleting) overlayMouseDownDismiss(e, onCancel);
        },
        onKeyDown: handleKeyDown,
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-delete-account-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-delete-account-title", className: contractStyles.title, children: "Delete account?" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.subtitle, children: "This permanently removes your marketplace profile. You will need to connect your API key again to use the extension." }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: contractStyles.checkboxLabel, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "input",
                  {
                    type: "checkbox",
                    className: contractStyles.checkbox,
                    checked: acknowledged,
                    disabled: deleting,
                    onChange: (e) => {
                      setAcknowledged(e.target.checked);
                      if (!e.target.checked) stopHold();
                    }
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "I understand that all data including my balance will be permanently lost." })
              ] }),
              error2 && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.error, role: "alert", children: error2 }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: contractStyles.actions, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: contractStyles.cancel,
                    onClick: onCancel,
                    disabled: deleting,
                    children: "Cancel"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "button",
                  {
                    type: "button",
                    className: `${contractStyles.confirm} ${contractStyles.confirmDanger}`,
                    disabled: !canHold,
                    "aria-describedby": "tlm-delete-hold-hint",
                    onPointerDown: (e) => {
                      if (!canHold || e.button !== 0) return;
                      e.preventDefault();
                      startHold();
                    },
                    onPointerUp: stopHold,
                    onPointerLeave: stopHold,
                    onPointerCancel: stopHold,
                    onContextMenu: (e) => e.preventDefault(),
                    children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "span",
                        {
                          className: contractStyles.confirmDangerFill,
                          style: { transform: `scaleX(${holdProgress})` },
                          "aria-hidden": "true"
                        }
                      ),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: contractStyles.confirmDangerLabel, children: deleting ? "Deleting…" : holdProgress > 0 ? "Keep holding…" : "Hold to confirm" })
                    ]
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("p", { id: "tlm-delete-hold-hint", className: contractStyles.holdHint, children: "Press and hold the confirm button for 5 seconds." })
            ]
          }
        )
      }
    );
  }
  const LEGACY_SLOT_ID = "tlm-chat-slot";
  const CHAT3 = {
    reference: "#people_panel_button",
    settings: "#notes_settings_button",
    utilityAnchors: [
      "#notes_settings_button",
      "#people_panel_button",
      "#notes_panel_button"
    ]
  };
  const CHAT2_FOOTER = '#chatRoot section[class*="chat-app__footer-wrapper"]';
  function getChat2SettingsButton() {
    var _a2;
    const byIcon = (_a2 = document.querySelector("#chatSettingIcon")) == null ? void 0 : _a2.closest("button");
    if (byIcon instanceof HTMLButtonElement) return byIcon;
    return document.querySelector(
      `${CHAT2_FOOTER} button[class*="chat-setting-button"]`
    );
  }
  function detectChatPanelVariant() {
    if (document.querySelector(CHAT3.settings)) return "chat3";
    if (getChat2SettingsButton()) return "chat2";
    return null;
  }
  function getChat2StyleReferenceButton() {
    return getChat2SettingsButton();
  }
  function getSettingsButton() {
    const variant = detectChatPanelVariant();
    if (variant === "chat3") {
      return document.querySelector(CHAT3.settings);
    }
    if (variant === "chat2") {
      return getChat2SettingsButton();
    }
    return null;
  }
  function getUtilityButtonGroup() {
    const variant = detectChatPanelVariant();
    if (variant === "chat3") {
      for (const selector of CHAT3.utilityAnchors) {
        const el = document.querySelector(selector);
        if ((el == null ? void 0 : el.parentElement) instanceof HTMLElement) {
          return el.parentElement;
        }
      }
      return null;
    }
    if (variant === "chat2") {
      return document.querySelector(CHAT2_FOOTER);
    }
    return null;
  }
  function removeLegacyChatSlot() {
    var _a2;
    (_a2 = document.getElementById(LEGACY_SLOT_ID)) == null ? void 0 : _a2.remove();
  }
  function placeMarketButton(button2) {
    removeLegacyChatSlot();
    const settings = getSettingsButton();
    const group2 = getUtilityButtonGroup();
    if (!group2 || !settings || settings.parentElement !== group2) {
      return false;
    }
    if (button2.parentElement !== group2 || button2.nextElementSibling !== settings) {
      group2.insertBefore(button2, settings);
    }
    return true;
  }
  function getReferenceButton() {
    const variant = detectChatPanelVariant();
    if (variant === "chat3") {
      return document.querySelector(CHAT3.reference);
    }
    if (variant === "chat2") {
      return getChat2StyleReferenceButton();
    }
    return null;
  }
  function applyChat2ButtonMetrics(button2, reference) {
    button2.style.setProperty("flex", "0 0 auto");
    button2.style.setProperty("flex-grow", "0");
    button2.style.setProperty("flex-shrink", "0");
    button2.style.setProperty("align-self", "center");
    button2.style.setProperty("min-width", "0");
    button2.style.setProperty("max-width", "none");
    const { width, height } = reference.getBoundingClientRect();
    if (width > 0) button2.style.setProperty("width", `${width}px`);
    if (height > 0) button2.style.setProperty("height", `${height}px`);
  }
  function syncButtonLayoutClasses(button2) {
    const variant = detectChatPanelVariant();
    const reference = getReferenceButton();
    if (!reference) return;
    button2.className = reference.className;
    if (variant === "chat2") {
      applyChat2ButtonMetrics(button2, reference);
    } else {
      button2.style.removeProperty("flex");
      button2.style.removeProperty("flex-grow");
      button2.style.removeProperty("flex-shrink");
      button2.style.removeProperty("align-self");
      button2.style.removeProperty("min-width");
      button2.style.removeProperty("max-width");
      button2.style.removeProperty("width");
      button2.style.removeProperty("height");
    }
  }
  function getReferenceIconClasses() {
    const reference = getReferenceButton();
    const svg = reference == null ? void 0 : reference.querySelector("svg");
    if ((svg == null ? void 0 : svg.className) && typeof svg.className === "string") {
      return svg.className;
    }
    if ((svg == null ? void 0 : svg.className) && "baseVal" in svg.className) {
      return svg.className.baseVal;
    }
    return "";
  }
  function useChatPanelAnchor() {
    const [anchor, setAnchor] = reactExports.useState(() => {
      removeLegacyChatSlot();
      return getUtilityButtonGroup();
    });
    reactExports.useEffect(() => {
      const sync = () => {
        removeLegacyChatSlot();
        const group2 = getUtilityButtonGroup();
        if (group2) setAnchor(group2);
      };
      if (!anchor) sync();
      const observer2 = new MutationObserver(sync);
      observer2.observe(document.documentElement, {
        childList: true,
        subtree: true
      });
      return () => observer2.disconnect();
    }, [anchor]);
    return anchor;
  }
  const STORAGE_KEY$7 = "panel_button_intro_seen";
  async function hasSeenPanelButtonTutorial() {
    try {
      return await getPlatformRuntime().storage.get(STORAGE_KEY$7) === true;
    } catch {
      return false;
    }
  }
  async function markPanelButtonTutorialSeen() {
    try {
      await getPlatformRuntime().storage.set(STORAGE_KEY$7, true);
    } catch {
    }
  }
  const FADE_MS$3 = 1e3;
  function usePanelButtonTutorial(buttonMounted) {
    const [phase, setPhase] = reactExports.useState("loading");
    const [backdropOpacity, setBackdropOpacity] = reactExports.useState(0);
    const dismissStarted = reactExports.useRef(false);
    reactExports.useEffect(() => {
      let cancelled = false;
      void hasSeenPanelButtonTutorial().then((seen) => {
        if (cancelled) return;
        setPhase(seen ? "done" : "visible");
      });
      return () => {
        cancelled = true;
      };
    }, []);
    reactExports.useEffect(() => {
      if (phase !== "visible" || !buttonMounted) return;
      const id2 = requestAnimationFrame(() => {
        requestAnimationFrame(() => setBackdropOpacity(1));
      });
      return () => cancelAnimationFrame(id2);
    }, [phase, buttonMounted]);
    const dismissTutorial = reactExports.useCallback(() => {
      if (phase !== "visible" || dismissStarted.current) return;
      dismissStarted.current = true;
      setPhase("dismissing");
      setBackdropOpacity(0);
      void markPanelButtonTutorialSeen();
    }, [phase]);
    const onBackdropTransitionEnd = reactExports.useCallback(
      (propertyName) => {
        if (propertyName !== "opacity" || phase !== "dismissing") return;
        setPhase("done");
      },
      [phase]
    );
    const showBackdrop = buttonMounted && (phase === "visible" || phase === "dismissing");
    return {
      showBackdrop,
      backdropOpacity,
      fadeMs: FADE_MS$3,
      dismissTutorial,
      onBackdropTransitionEnd,
      tutorialBlocking: phase === "visible"
    };
  }
  function MarketIcon({ className }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      ShieldUser,
      {
        className,
        size: 24,
        strokeWidth: 2,
        color: "#fff",
        "aria-hidden": true
      }
    );
  }
  const COUNTDOWN_STYLE = {
    display: "block",
    fontSize: "11px",
    fontWeight: 700,
    lineHeight: 1,
    color: "#fff",
    letterSpacing: "0.02em",
    fontVariantNumeric: "tabular-nums",
    whiteSpace: "nowrap"
  };
  const COUNTDOWN_GRADIENT = "linear-gradient(180deg, #e8a43a 0%, #c45c1a 100%)";
  const ALERT_GRADIENT = "linear-gradient(#cc7032 0,#b3382c)";
  function MarketPanelButton({
    onClick,
    sidebarOpen,
    alertActive,
    contractActive,
    contractSecondsRemaining,
    redeemingContractActive,
    redeemingSecondsRemaining,
    bountyContractActive,
    bountySecondsRemaining,
    productivityBoostContractActive,
    productivityBoostSecondsRemaining,
    embargoContractActive,
    embargoSecondsRemaining,
    flightDelayContractActive,
    flightDelaySecondsRemaining,
    simpleServiceContractActive,
    simpleServiceSecondsRemaining
  }) {
    var _a2;
    const anchor = useChatPanelAnchor();
    const buttonRef = reactExports.useRef(null);
    const buttonMounted = Boolean(anchor);
    const {
      showBackdrop,
      backdropOpacity,
      fadeMs,
      dismissTutorial,
      onBackdropTransitionEnd,
      tutorialBlocking
    } = usePanelButtonTutorial(buttonMounted);
    const iconClass = getReferenceIconClasses();
    const buttonClassName = ((_a2 = getReferenceButton()) == null ? void 0 : _a2.className) ?? "";
    const handleClick = reactExports.useCallback(() => {
      if (tutorialBlocking) {
        dismissTutorial();
      }
      onClick();
    }, [tutorialBlocking, dismissTutorial, onClick]);
    const countdownActive = contractActive || redeemingContractActive || bountyContractActive || productivityBoostContractActive || embargoContractActive || flightDelayContractActive || simpleServiceContractActive;
    const secondsRemaining = contractActive ? contractSecondsRemaining : redeemingContractActive ? redeemingSecondsRemaining : bountyContractActive ? bountySecondsRemaining : productivityBoostContractActive ? productivityBoostSecondsRemaining : embargoContractActive ? embargoSecondsRemaining : flightDelayContractActive ? flightDelaySecondsRemaining : simpleServiceSecondsRemaining;
    reactExports.useLayoutEffect(() => {
      const button2 = buttonRef.current;
      if (!button2) return;
      placeMarketButton(button2);
      syncButtonLayoutClasses(button2);
      if (countdownActive) {
        button2.style.setProperty("background", COUNTDOWN_GRADIENT, "important");
        button2.style.setProperty(
          "background-image",
          COUNTDOWN_GRADIENT,
          "important"
        );
      } else if (alertActive) {
        button2.style.setProperty("background", ALERT_GRADIENT, "important");
        button2.style.setProperty("background-image", ALERT_GRADIENT, "important");
      } else {
        applyBrandButtonBackground(button2);
      }
      button2.style.removeProperty("top");
      button2.style.removeProperty("left");
      button2.style.removeProperty("right");
      button2.style.removeProperty("bottom");
      button2.style.removeProperty("position");
      button2.style.removeProperty("z-index");
      if (sidebarOpen && !countdownActive && !alertActive) {
        button2.style.setProperty(
          "box-shadow",
          "inset 0 0 0 2px rgba(255, 255, 255, 0.35)",
          "important"
        );
      } else {
        button2.style.removeProperty("box-shadow");
      }
    }, [sidebarOpen, anchor, buttonClassName, countdownActive, alertActive]);
    if (!anchor) return null;
    const countdownLabel = formatCountdown(secondsRemaining);
    const countdownTitle = contractActive ? `Sell contract time remaining: ${countdownLabel}` : redeemingContractActive ? `Xanax fulfillment time remaining: ${countdownLabel}` : bountyContractActive ? `Bounty fulfillment time remaining: ${countdownLabel}` : productivityBoostContractActive ? `Productivity boost time remaining: ${countdownLabel}` : embargoContractActive ? `Embargo time remaining: ${countdownLabel}` : flightDelayContractActive ? `Flight delay time remaining: ${countdownLabel}` : `Service time remaining: ${countdownLabel}`;
    const alertTitle = "Market alert: a matching contract is available";
    const defaultTitle = sidebarOpen ? `Close ${BRAND_NAME}` : `Open ${BRAND_NAME}`;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PanelButtonTutorial,
        {
          visible: showBackdrop,
          opacity: backdropOpacity,
          fadeMs,
          targetRef: buttonRef,
          onTransitionEnd: onBackdropTransitionEnd
        }
      ),
      reactDomExports.createPortal(
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            ref: buttonRef,
            type: "button",
            id: "losses_market_panel_button",
            className: buttonClassName,
            title: countdownActive ? countdownTitle : alertActive ? alertTitle : BRAND_NAME,
            onClick: handleClick,
            "aria-label": countdownActive ? countdownTitle : alertActive ? alertTitle : defaultTitle,
            "aria-expanded": sidebarOpen,
            children: countdownActive ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { style: COUNTDOWN_STYLE, children: countdownLabel }) : /* @__PURE__ */ jsxRuntimeExports.jsx(MarketIcon, { className: iconClass })
          }
        ),
        anchor
      )
    ] });
  }
  const OD_PAYOUT_PTS = {
    xanax: 3e7,
    ecstasy: 2e7
  };
  function isEventsPage() {
    if (typeof location === "undefined") return false;
    if (!/\/page\.php$/i.test(location.pathname)) return false;
    return new URLSearchParams(location.search).get("sid") === "events";
  }
  function detectOdDrug(message) {
    if (!/overdos/i.test(message)) return null;
    if (/\bxanax\b/i.test(message)) return "xanax";
    if (/\becstasy\b/i.test(message)) return "ecstasy";
    return null;
  }
  function odPayoutLabel(drug) {
    return `Get paid ${OD_PAYOUT_PTS[drug].toLocaleString("en-US")} PTS`;
  }
  const LINK_MARKER_ATTR = "data-tlm-od-ad";
  const PROCESSED_ATTR = "data-tlm-od-seen";
  const LINK_COLOR = "#3aa655";
  const MESSAGE_SELECTOR = 'p[class*="message"]';
  function styleLink(link2) {
    Object.assign(link2.style, {
      marginLeft: "6px",
      color: LINK_COLOR,
      fontWeight: "700",
      cursor: "pointer",
      textDecorationLine: "underline",
      textDecorationStyle: "dotted",
      textDecorationColor: LINK_COLOR,
      textUnderlineOffset: "2px",
      whiteSpace: "nowrap"
    });
  }
  function OdInsuranceAd({ onActivate }) {
    const onActivateRef = reactExports.useRef(onActivate);
    onActivateRef.current = onActivate;
    reactExports.useEffect(() => {
      const injected = [];
      const buildLink = (drug) => {
        const link2 = document.createElement("span");
        link2.setAttribute(LINK_MARKER_ATTR, "1");
        link2.setAttribute("role", "button");
        link2.tabIndex = 0;
        link2.textContent = odPayoutLabel(drug);
        styleLink(link2);
        const activate = (e) => {
          e.preventDefault();
          e.stopPropagation();
          onActivateRef.current(drug);
        };
        link2.addEventListener("click", activate);
        link2.addEventListener("keydown", (e) => {
          if (e.key === "Enter" || e.key === " ") activate(e);
        });
        link2.addEventListener("mouseenter", () => {
          link2.style.textDecorationStyle = "solid";
        });
        link2.addEventListener("mouseleave", () => {
          link2.style.textDecorationStyle = "dotted";
        });
        return link2;
      };
      const scan = () => {
        if (!isEventsPage()) return;
        const messages = document.querySelectorAll(MESSAGE_SELECTOR);
        messages.forEach((msg) => {
          if (msg.getAttribute(PROCESSED_ATTR) === "1") {
            if (msg.querySelector(`[${LINK_MARKER_ATTR}]`)) return;
          }
          const drug = detectOdDrug(msg.textContent ?? "");
          if (!drug) {
            msg.setAttribute(PROCESSED_ATTR, "1");
            return;
          }
          const link2 = buildLink(drug);
          msg.appendChild(link2);
          msg.setAttribute(PROCESSED_ATTR, "1");
          injected.push(link2);
        });
      };
      let rafId = 0;
      const scheduleScan = () => {
        if (rafId) return;
        rafId = requestAnimationFrame(() => {
          rafId = 0;
          scan();
        });
      };
      scan();
      const observer2 = new MutationObserver(scheduleScan);
      observer2.observe(document.body, { childList: true, subtree: true });
      return () => {
        if (rafId) cancelAnimationFrame(rafId);
        observer2.disconnect();
        for (const link2 of injected) link2.remove();
      };
    }, []);
    return null;
  }
  const XANAX_ITEM_ID = 206;
  const SEND_FORM_AUTOFILLED_ATTR = "data-tlm-send-autofilled";
  function isItemsPage() {
    if (typeof location === "undefined") return false;
    return /\/item\.php$/i.test(location.pathname);
  }
  function findXanaxItemRow() {
    return document.querySelector(`li[data-item="${XANAX_ITEM_ID}"]`);
  }
  function getDrugsCategoryTab() {
    return document.querySelector(
      '#category-wrap a.drugs-category-icon, #category-wrap li[data-type="Drug"] a'
    );
  }
  function getSendForm(row2) {
    return row2.querySelector('form[act="send"]');
  }
  function getSendButton(row2) {
    return row2.querySelector(
      'li.send[data-action="send"] button, li.send button.option-send'
    );
  }
  function setNativeInputValue$1(input2, value) {
    const proto = Object.getPrototypeOf(input2);
    const descriptor = Object.getOwnPropertyDescriptor(proto, "value");
    const setter = descriptor == null ? void 0 : descriptor.set;
    if (setter) {
      setter.call(input2, value);
    } else {
      input2.value = value;
    }
    input2.dispatchEvent(new Event("input", { bubbles: true }));
    input2.dispatchEvent(new Event("change", { bubbles: true }));
    input2.dispatchEvent(new KeyboardEvent("keyup", { bubbles: true }));
  }
  function fillSendForm(form2, { recipientId, amount }) {
    if (form2.getAttribute(SEND_FORM_AUTOFILLED_ATTR) === "1") return false;
    if (recipientId <= 0 || amount <= 0) return false;
    const userInput = form2.querySelector('input[name="userID"]');
    const amountInput = form2.querySelector(
      'input.input-money[type="text"]'
    );
    if (!userInput || !amountInput) return false;
    const amountHidden = form2.querySelector(
      'input[name="amount"]'
    );
    const max = Number(amountInput.getAttribute("data-max"));
    const clamped = Number.isFinite(max) && max > 0 ? Math.min(amount, max) : amount;
    const finalAmount = Math.max(1, Math.floor(clamped));
    setNativeInputValue$1(userInput, String(recipientId));
    setNativeInputValue$1(amountInput, String(finalAmount));
    if (amountHidden) setNativeInputValue$1(amountHidden, String(finalAmount));
    form2.setAttribute(SEND_FORM_AUTOFILLED_ATTR, "1");
    return true;
  }
  function ItemSendAutofill({ recipientId, amount }) {
    const recipientRef = reactExports.useRef(recipientId);
    const amountRef = reactExports.useRef(amount);
    recipientRef.current = recipientId;
    amountRef.current = amount;
    reactExports.useEffect(() => {
      if (!isItemsPage()) return;
      if (recipientRef.current <= 0 || amountRef.current <= 0) return;
      let finished = false;
      let drugsTabClicked = false;
      let sendClicked = false;
      let rafId = 0;
      const observer2 = new MutationObserver(() => schedule());
      const finish = () => {
        finished = true;
        if (rafId) cancelAnimationFrame(rafId);
        observer2.disconnect();
      };
      const run = () => {
        if (finished) return;
        const row2 = findXanaxItemRow();
        if (!row2) {
          if (!drugsTabClicked) {
            const tab2 = getDrugsCategoryTab();
            if (tab2) {
              drugsTabClicked = true;
              tab2.click();
            }
          }
          return;
        }
        const form2 = getSendForm(row2);
        if (form2) {
          fillSendForm(form2, {
            recipientId: recipientRef.current,
            amount: amountRef.current
          });
          finish();
          return;
        }
        if (!sendClicked) {
          const button2 = getSendButton(row2);
          if (button2) {
            sendClicked = true;
            button2.click();
          }
        }
      };
      function schedule() {
        if (rafId || finished) return;
        rafId = requestAnimationFrame(() => {
          rafId = 0;
          run();
        });
      }
      observer2.observe(document.body, { childList: true, subtree: true });
      run();
      return () => {
        if (rafId) cancelAnimationFrame(rafId);
        observer2.disconnect();
      };
    }, []);
    return null;
  }
  const TORN_BOUNTY_CAP = 10;
  const BOUNTY_REASON_TEXT = BRAND_NAME;
  const REWARD_FILLED_ATTR = "data-tp-bounty-reward";
  const REASON_FILLED_ATTR = "data-tp-bounty-reason";
  const AD_WIRED_ATTR = "data-tp-bounty-ad";
  const TARGET_STEP_ATTR = "data-tp-bounty-step";
  const STYLE_ID = "tp-bounty-placement-styles";
  const SEG_CLASS = "tp-bty-seg";
  const SEG_FLASH_CLASS = "tp-bty-seg--flash";
  const SEG_VISIBLE_CLASS = "tp-bty-seg--visible";
  const SEG_LABEL_CLASS = "tp-bty-seg-label";
  const CALLOUT_CLASS = "tp-bty-callout";
  const CALLOUT_OPEN_CLASS = "is-open";
  const CALLOUT_CTA_CLASS = "tp-bty-callout-cta";
  const CALLOUT_DISMISS_CLASS = "tp-bty-callout-x";
  const STEP_TARGET_CLASS = "tp-bty-step-target";
  const STEP_FLAG_CLASS = "tp-bty-step-flag";
  function isBountiesPage() {
    if (typeof location === "undefined") return false;
    return /\/bounties\.php/i.test(location.pathname);
  }
  function getAddBountiesForm() {
    return document.querySelector(
      "form.add-bounties-form, .add-bounties-wrap form"
    );
  }
  function setNativeInputValue(input2, value) {
    const proto = Object.getPrototypeOf(input2);
    const descriptor = Object.getOwnPropertyDescriptor(proto, "value");
    const setter = descriptor == null ? void 0 : descriptor.set;
    if (setter) {
      setter.call(input2, value);
    } else {
      input2.value = value;
    }
    input2.dispatchEvent(new Event("input", { bubbles: true }));
    input2.dispatchEvent(new Event("change", { bubbles: true }));
    input2.dispatchEvent(new KeyboardEvent("keyup", { bubbles: true }));
  }
  function getTargetInput(form2) {
    return form2.querySelector('input[name="target"]');
  }
  function targetMatches(form2, targetId) {
    var _a2;
    if (targetId <= 0) return false;
    const value = ((_a2 = getTargetInput(form2)) == null ? void 0 : _a2.value) ?? "";
    return value.includes(`[${targetId}]`);
  }
  function fillReward(form2, reward) {
    if (!Number.isFinite(reward) || reward <= 0) return false;
    const group2 = form2.querySelector(".input-money-group");
    if (!group2) return false;
    if (group2.getAttribute(REWARD_FILLED_ATTR) === "1") return false;
    const visible = group2.querySelector(
      'input.input-money[type="text"]'
    );
    const hidden = group2.querySelector(
      'input.input-money[type="hidden"][name="reward"], input[name="reward"]'
    );
    if (!visible) return false;
    const amount = String(Math.max(1, Math.floor(reward)));
    visible.setAttribute("data-money", amount);
    if (hidden) hidden.setAttribute("data-money", amount);
    setNativeInputValue(visible, amount);
    if (hidden) setNativeInputValue(hidden, amount);
    group2.setAttribute(REWARD_FILLED_ATTR, "1");
    return true;
  }
  function fillReason(form2, text2 = BOUNTY_REASON_TEXT) {
    const input2 = form2.querySelector(
      'input.reason-input[name="reason"], input[name="reason"]'
    );
    if (!input2) return false;
    if (input2.getAttribute(REASON_FILLED_ATTR) === "1") return false;
    setNativeInputValue(input2, text2.slice(0, 30));
    input2.setAttribute(REASON_FILLED_ATTR, "1");
    return true;
  }
  function getQuantitySlider(form2) {
    return form2.querySelector("#qty-range-slider, .range-slider");
  }
  function getSliderHandle(form2) {
    const slider = getQuantitySlider(form2);
    return (slider == null ? void 0 : slider.querySelector(".ui-slider-handle")) ?? null;
  }
  function getSliderWrap(form2) {
    var _a2;
    return form2.querySelector(".range-slider-wrap") ?? ((_a2 = getQuantitySlider(form2)) == null ? void 0 : _a2.parentElement) ?? null;
  }
  function getStepItems(form2) {
    return Array.from(
      form2.querySelectorAll(".slider-steps > li")
    );
  }
  function markQuantityTarget(form2, quantity2) {
    var _a2;
    const steps = getStepItems(form2);
    if (steps.length === 0) return;
    const target2 = Math.min(Math.max(1, Math.round(quantity2)), steps.length);
    const stepsRoot = steps[0].parentElement;
    if (!stepsRoot) return;
    if (stepsRoot.getAttribute(TARGET_STEP_ATTR) === String(target2)) return;
    for (const li2 of steps) {
      li2.classList.remove(STEP_TARGET_CLASS);
      (_a2 = li2.querySelector(`.${STEP_FLAG_CLASS}`)) == null ? void 0 : _a2.remove();
    }
    const li = steps[target2 - 1];
    if (!li) return;
    li.classList.add(STEP_TARGET_CLASS);
    const flag = document.createElement("div");
    flag.className = STEP_FLAG_CLASS;
    flag.textContent = `Drag to ${target2}`;
    li.appendChild(flag);
    stepsRoot.setAttribute(TARGET_STEP_ATTR, String(target2));
  }
  function readQuantity(form2, handle) {
    const fromHandle = parseInt((handle.textContent ?? "").trim(), 10);
    if (Number.isFinite(fromHandle) && fromHandle > 0) return fromHandle;
    const hidden = form2.querySelector('input[name="quantity"]');
    const v = Number(hidden == null ? void 0 : hidden.value);
    return Number.isFinite(v) ? v : 0;
  }
  function setupBountyAd(form2, onOpenPanel) {
    const qtyWrap = form2.querySelector(".qty-slider-wrap");
    const wrap2 = getSliderWrap(form2);
    const slider = getQuantitySlider(form2);
    const handle = getSliderHandle(form2);
    const steps = form2.querySelector(".slider-steps");
    if (!qtyWrap || !wrap2 || !slider || !handle || !steps) return null;
    if (wrap2.getAttribute(AD_WIRED_ATTR) === "1") return null;
    wrap2.setAttribute(AD_WIRED_ATTR, "1");
    ensureBountyStyles();
    const prevQtyPosition = qtyWrap.style.position;
    if (getComputedStyle(qtyWrap).position === "static") {
      qtyWrap.style.position = "relative";
    }
    const seg = document.createElement("div");
    seg.className = SEG_CLASS;
    seg.setAttribute("role", "button");
    seg.tabIndex = 0;
    seg.title = `Torn stops at ${TORN_BOUNTY_CAP} — ${BRAND_NAME} doesn't`;
    slider.appendChild(seg);
    const segLabel = document.createElement("div");
    segLabel.className = SEG_LABEL_CLASS;
    segLabel.textContent = BRAND_NAME;
    qtyWrap.appendChild(segLabel);
    const callout = buildCallout(onOpenPanel);
    qtyWrap.insertAdjacentElement("afterend", callout);
    const scale2 = TORN_BOUNTY_CAP / (TORN_BOUNTY_CAP + 1);
    const layout2 = () => {
      const full = qtyWrap.clientWidth;
      if (full <= 0) return;
      const barWidth = full * scale2;
      const segWidth = full / (TORN_BOUNTY_CAP + 1);
      slider.style.width = `${barWidth}px`;
      steps.style.transformOrigin = "left center";
      steps.style.transform = `scaleX(${scale2})`;
      const track = slider.querySelector(".range-slider-bg, .ui-slider-range") ?? slider;
      seg.style.top = `${track.offsetTop}px`;
      seg.style.height = `${track.offsetHeight}px`;
      seg.style.width = `${segWidth}px`;
      segLabel.style.top = `${steps.offsetTop}px`;
      segLabel.style.left = `${barWidth}px`;
      segLabel.style.width = `${segWidth}px`;
    };
    layout2();
    let resizeObserver = null;
    if (typeof ResizeObserver !== "undefined") {
      resizeObserver = new ResizeObserver(layout2);
      resizeObserver.observe(qtyWrap);
    }
    const refreshCap = () => {
      const atCap = readQuantity(form2, handle) >= TORN_BOUNTY_CAP;
      seg.classList.toggle(SEG_VISIBLE_CLASS, atCap);
      segLabel.classList.toggle(SEG_VISIBLE_CLASS, atCap);
    };
    refreshCap();
    const valueObserver = new MutationObserver(refreshCap);
    valueObserver.observe(handle, {
      childList: true,
      characterData: true,
      subtree: true,
      attributes: true
    });
    const flashSeg = () => {
      seg.classList.remove(SEG_FLASH_CLASS);
      void seg.offsetWidth;
      seg.classList.add(SEG_FLASH_CLASS);
    };
    const reveal = () => {
      callout.classList.add(CALLOUT_OPEN_CLASS);
      flashSeg();
    };
    const onActivate = (e) => {
      e.preventDefault();
      e.stopPropagation();
      reveal();
    };
    seg.addEventListener("click", onActivate);
    segLabel.addEventListener("click", onActivate);
    seg.addEventListener("keydown", (e) => {
      if (e.key === "Enter" || e.key === " ") onActivate(e);
    });
    let dragging = false;
    const onPointerMove = (e) => {
      if (!dragging) return;
      refreshCap();
      if (e.clientX > slider.getBoundingClientRect().right + 6) reveal();
    };
    const onPointerUp = () => {
      dragging = false;
      document.removeEventListener("pointermove", onPointerMove);
      document.removeEventListener("pointerup", onPointerUp);
    };
    const onHandleDown = () => {
      dragging = true;
      document.addEventListener("pointermove", onPointerMove);
      document.addEventListener("pointerup", onPointerUp);
    };
    handle.addEventListener("pointerdown", onHandleDown);
    const dispose = () => {
      resizeObserver == null ? void 0 : resizeObserver.disconnect();
      valueObserver.disconnect();
      document.removeEventListener("pointermove", onPointerMove);
      document.removeEventListener("pointerup", onPointerUp);
      handle.removeEventListener("pointerdown", onHandleDown);
      seg.remove();
      segLabel.remove();
      callout.remove();
      slider.style.width = "";
      steps.style.transform = "";
      steps.style.transformOrigin = "";
      qtyWrap.style.position = prevQtyPosition;
      wrap2.removeAttribute(AD_WIRED_ATTR);
    };
    return { reveal, dispose };
  }
  function buildCallout(onOpenPanel) {
    const callout = document.createElement("div");
    callout.className = CALLOUT_CLASS;
    const dismiss = document.createElement("button");
    dismiss.type = "button";
    dismiss.className = CALLOUT_DISMISS_CLASS;
    dismiss.setAttribute("aria-label", "Dismiss");
    dismiss.textContent = "×";
    dismiss.addEventListener("click", (e) => {
      e.preventDefault();
      e.stopPropagation();
      callout.classList.remove(CALLOUT_OPEN_CLASS);
    });
    const title2 = document.createElement("div");
    title2.className = "tp-bty-callout-title";
    title2.textContent = `Hit Torn's ${TORN_BOUNTY_CAP}-bounty cap?`;
    const body2 = document.createElement("div");
    body2.className = "tp-bty-callout-body";
    body2.textContent = `${BRAND_NAME} has no limit — set your price and players place every bounty for you.`;
    const cta = document.createElement("button");
    cta.type = "button";
    cta.className = CALLOUT_CTA_CLASS;
    cta.textContent = `Show me how`;
    cta.addEventListener("click", (e) => {
      e.preventDefault();
      e.stopPropagation();
      onOpenPanel();
    });
    callout.append(dismiss, title2, body2, cta);
    return callout;
  }
  function ensureBountyStyles() {
    if (document.getElementById(STYLE_ID)) return;
    const style = document.createElement("style");
    style.id = STYLE_ID;
    style.textContent = `
.${SEG_CLASS} {
  position: absolute;
  left: 100%;
  border-radius: 0 2px 2px 0;
  background: ${BRAND_GRADIENT};
  cursor: pointer;
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.2);
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.25s ease;
  z-index: 3;
}
/* The 11th only appears once the slider hits Torn's cap. */
.${SEG_CLASS}.${SEG_VISIBLE_CLASS} {
  opacity: 1;
  pointer-events: auto;
}
.${SEG_CLASS}.${SEG_VISIBLE_CLASS}:hover,
.${SEG_CLASS}.${SEG_VISIBLE_CLASS}:focus-visible {
  outline: none;
  filter: brightness(1.12);
}
.${SEG_CLASS}.${SEG_FLASH_CLASS} { animation: tp-bty-seg-flash 0.6s ease; }
@keyframes tp-bty-seg-flash {
  0%, 100% { box-shadow: inset 0 0 0 1px rgba(255,255,255,0.2); }
  45% { box-shadow: inset 0 0 0 1px rgba(255,255,255,0.4), 0 0 9px 1px rgba(112,139,219,0.85); }
}
.${SEG_LABEL_CLASS} {
  position: absolute;
  text-align: center;
  white-space: nowrap;
  font-weight: 700;
  font-size: 11px;
  color: #9fb0ff;
  text-shadow: 0 0 5px rgba(112, 139, 219, 0.55);
  cursor: pointer;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.25s ease;
}
.${SEG_LABEL_CLASS}.${SEG_VISIBLE_CLASS} {
  opacity: 1;
  pointer-events: auto;
}
.${CALLOUT_CLASS} {
  display: none;
  position: relative;
  margin: 16px 0 6px;
  max-width: 470px;
  padding: 11px 34px 12px 14px;
  border-radius: 6px;
  background: #1c1c1c;
  border: 1px solid rgba(255, 255, 255, 0.09);
  border-left: 3px solid #3f43cf;
  color: #cdcdcd;
  font-size: 12px;
  box-shadow: 0 8px 22px rgba(0, 0, 0, 0.5);
}
.${CALLOUT_CLASS}.${CALLOUT_OPEN_CLASS} {
  display: block;
  animation: tp-bty-callout-in 0.2s ease;
}
@keyframes tp-bty-callout-in {
  from { opacity: 0; transform: translateY(-4px); }
  to { opacity: 1; transform: translateY(0); }
}
.tp-bty-callout-title {
  font-weight: 700;
  color: #fff;
  margin-bottom: 3px;
}
.tp-bty-callout-body {
  opacity: 0.82;
  margin-bottom: 10px;
  line-height: 1.4;
}
.${CALLOUT_CTA_CLASS} {
  appearance: none;
  border: 0;
  border-radius: 5px;
  padding: 6px 14px;
  background: ${BRAND_GRADIENT};
  color: #fff;
  font-size: 12px;
  font-weight: 700;
  cursor: pointer;
}
.${CALLOUT_CTA_CLASS}:hover { filter: brightness(1.08); }
.${CALLOUT_DISMISS_CLASS} {
  position: absolute;
  top: 4px;
  right: 6px;
  appearance: none;
  border: 0;
  background: transparent;
  color: inherit;
  opacity: 0.55;
  font-size: 16px;
  line-height: 1;
  cursor: pointer;
}
.${CALLOUT_DISMISS_CLASS}:hover { opacity: 1; }
.slider-steps > li.${STEP_TARGET_CLASS} {
  position: relative;
  color: #708bdb;
  font-weight: 700;
}
.${STEP_FLAG_CLASS} {
  position: absolute;
  bottom: calc(100% + 6px);
  left: 50%;
  transform: translateX(-50%);
  white-space: nowrap;
  padding: 2px 7px;
  border-radius: 5px;
  background: ${BRAND_GRADIENT};
  color: #fff;
  font-size: 10px;
  font-weight: 700;
  line-height: 1.2;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  animation: tp-bty-bob 1.4s ease-in-out infinite;
  z-index: 4;
}
.${STEP_FLAG_CLASS}::after {
  content: '';
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  border: 4px solid transparent;
  border-top-color: #3f43cf;
}
@keyframes tp-bty-bob {
  0%, 100% { transform: translateX(-50%) translateY(0); }
  50% { transform: translateX(-50%) translateY(-3px); }
}
`;
    (document.head ?? document.documentElement).appendChild(style);
  }
  function BountyPlacementAutofill({
    contract,
    onOpenPanel
  }) {
    const contractRef = reactExports.useRef(contract);
    contractRef.current = contract;
    const onOpenPanelRef = reactExports.useRef(onOpenPanel);
    onOpenPanelRef.current = onOpenPanel;
    const scheduleRef = reactExports.useRef(null);
    reactExports.useEffect(() => {
      if (!isBountiesPage()) return;
      let disposed = false;
      let rafId = 0;
      let ad = null;
      const run = () => {
        if (disposed) return;
        const form2 = getAddBountiesForm();
        if (!form2) return;
        const wired = setupBountyAd(form2, () => onOpenPanelRef.current());
        if (wired) ad = wired;
        const c = contractRef.current;
        if (c) {
          if (targetMatches(form2, c.targetId)) {
            fillReward(form2, c.rewardPerHosp);
            fillReason(form2);
          }
          markQuantityTarget(form2, c.quantityNeeded);
        }
      };
      const schedule = () => {
        if (rafId || disposed) return;
        rafId = requestAnimationFrame(() => {
          rafId = 0;
          run();
        });
      };
      scheduleRef.current = schedule;
      const observer2 = new MutationObserver(schedule);
      observer2.observe(document.body, { childList: true, subtree: true });
      run();
      return () => {
        disposed = true;
        scheduleRef.current = null;
        if (rafId) cancelAnimationFrame(rafId);
        observer2.disconnect();
        ad == null ? void 0 : ad.dispose();
      };
    }, []);
    reactExports.useEffect(() => {
      var _a2;
      (_a2 = scheduleRef.current) == null ? void 0 : _a2.call(scheduleRef);
    }, [contract == null ? void 0 : contract.targetId, contract == null ? void 0 : contract.rewardPerHosp, contract == null ? void 0 : contract.quantityNeeded]);
    return null;
  }
  const NOOP_VALUE$1 = {
    phase: "idle",
    active: false,
    startTour: () => {
    },
    cancelTour: () => {
    },
    notifyOtherCategoryOpened: () => {
    },
    notifyInsuranceSelected: () => {
    }
  };
  const InsuranceAdTourContext = reactExports.createContext(NOOP_VALUE$1);
  function useInsuranceAdTourContext() {
    return reactExports.useContext(InsuranceAdTourContext);
  }
  const InsuranceAdTourProvider = InsuranceAdTourContext.Provider;
  function useInsuranceAdTourState({
    mode,
    sidebarOpen,
    onOpenSidebar
  }) {
    const [phase, setPhase] = reactExports.useState("idle");
    const onOpenSidebarRef = reactExports.useRef(onOpenSidebar);
    onOpenSidebarRef.current = onOpenSidebar;
    const startTour = reactExports.useCallback(() => {
      onOpenSidebarRef.current();
      setPhase(mode === "selling" ? "otherCard" : "buyTab");
    }, [mode]);
    const cancelTour = reactExports.useCallback(() => setPhase("idle"), []);
    const notifyOtherCategoryOpened = reactExports.useCallback(() => {
      setPhase((prev) => prev === "otherCard" ? "insuranceCard" : prev);
    }, []);
    const notifyInsuranceSelected = reactExports.useCallback(() => {
      setPhase((prev) => prev === "insuranceCard" ? "idle" : prev);
    }, []);
    reactExports.useEffect(() => {
      if (phase === "buyTab" && mode === "selling") setPhase("otherCard");
    }, [phase, mode]);
    reactExports.useEffect(() => {
      if ((phase === "otherCard" || phase === "insuranceCard") && mode !== "selling") {
        setPhase("buyTab");
      }
    }, [phase, mode]);
    reactExports.useEffect(() => {
      if (!sidebarOpen && phase !== "idle") setPhase("idle");
    }, [sidebarOpen, phase]);
    return {
      phase,
      active: phase !== "idle",
      startTour,
      cancelTour,
      notifyOtherCategoryOpened,
      notifyInsuranceSelected
    };
  }
  const NOOP_VALUE = {
    phase: "idle",
    active: false,
    startTour: () => {
    },
    cancelTour: () => {
    },
    notifyDisruptCategoryOpened: () => {
    },
    notifyBountiesSelected: () => {
    }
  };
  const BountyAdTourContext = reactExports.createContext(NOOP_VALUE);
  function useBountyAdTourContext() {
    return reactExports.useContext(BountyAdTourContext);
  }
  const BountyAdTourProvider = BountyAdTourContext.Provider;
  function useBountyAdTourState({
    mode,
    sidebarOpen,
    onOpenSidebar
  }) {
    const [phase, setPhase] = reactExports.useState("idle");
    const onOpenSidebarRef = reactExports.useRef(onOpenSidebar);
    onOpenSidebarRef.current = onOpenSidebar;
    const startTour = reactExports.useCallback(() => {
      onOpenSidebarRef.current();
      setPhase(mode === "selling" ? "disruptCard" : "buyTab");
    }, [mode]);
    const cancelTour = reactExports.useCallback(() => setPhase("idle"), []);
    const notifyDisruptCategoryOpened = reactExports.useCallback(() => {
      setPhase((prev) => prev === "disruptCard" ? "bountiesCard" : prev);
    }, []);
    const notifyBountiesSelected = reactExports.useCallback(() => {
      setPhase((prev) => prev === "bountiesCard" ? "idle" : prev);
    }, []);
    reactExports.useEffect(() => {
      if (phase === "buyTab" && mode === "selling") setPhase("disruptCard");
    }, [phase, mode]);
    reactExports.useEffect(() => {
      if ((phase === "disruptCard" || phase === "bountiesCard") && mode !== "selling") {
        setPhase("buyTab");
      }
    }, [phase, mode]);
    reactExports.useEffect(() => {
      if (!sidebarOpen && phase !== "idle") setPhase("idle");
    }, [sidebarOpen, phase]);
    return {
      phase,
      active: phase !== "idle",
      startTour,
      cancelTour,
      notifyDisruptCategoryOpened,
      notifyBountiesSelected
    };
  }
  const STORAGE_KEY$6 = "withdrawing_tab_intro_seen";
  async function hasSeenWithdrawingTabTutorial() {
    try {
      return await getPlatformRuntime().storage.get(STORAGE_KEY$6) === true;
    } catch {
      return false;
    }
  }
  async function markWithdrawingTabTutorialSeen() {
    try {
      await getPlatformRuntime().storage.set(STORAGE_KEY$6, true);
    } catch {
    }
  }
  const FADE_MS$2 = 1e3;
  function useWithdrawingBalanceTutorial(enabled) {
    const [phase, setPhase] = reactExports.useState("loading");
    const [backdropOpacity, setBackdropOpacity] = reactExports.useState(0);
    const dismissStarted = reactExports.useRef(false);
    const storageChecked = reactExports.useRef(false);
    reactExports.useEffect(() => {
      if (storageChecked.current) return;
      storageChecked.current = true;
      let cancelled = false;
      void hasSeenWithdrawingTabTutorial().then((seen) => {
        if (cancelled) return;
        setPhase(seen ? "done" : "visible");
      });
      return () => {
        cancelled = true;
      };
    }, []);
    reactExports.useEffect(() => {
      if (phase !== "visible" || !enabled) return;
      const id2 = requestAnimationFrame(() => {
        requestAnimationFrame(() => setBackdropOpacity(1));
      });
      return () => cancelAnimationFrame(id2);
    }, [phase, enabled]);
    reactExports.useEffect(() => {
      if (phase !== "visible" || enabled) return;
      setBackdropOpacity(0);
    }, [phase, enabled]);
    const dismissTutorial = reactExports.useCallback(() => {
      if (phase !== "visible" || dismissStarted.current) return;
      dismissStarted.current = true;
      setPhase("dismissing");
      setBackdropOpacity(0);
      void markWithdrawingTabTutorialSeen();
    }, [phase]);
    const onBackdropTransitionEnd = reactExports.useCallback(
      (propertyName) => {
        if (propertyName !== "opacity" || phase !== "dismissing") return;
        setPhase("done");
      },
      [phase]
    );
    const showBackdrop = enabled && (phase === "visible" || phase === "dismissing");
    return {
      showBackdrop,
      backdropOpacity,
      fadeMs: FADE_MS$2,
      dismissTutorial,
      onBackdropTransitionEnd,
      tutorialBlocking: enabled && phase === "visible"
    };
  }
  const STORAGE_KEY$5 = "sell_tab_intro_seen";
  async function hasSeenSellTabTutorial() {
    try {
      return await getPlatformRuntime().storage.get(STORAGE_KEY$5) === true;
    } catch {
      return false;
    }
  }
  async function markSellTabTutorialSeen() {
    try {
      await getPlatformRuntime().storage.set(STORAGE_KEY$5, true);
    } catch {
    }
  }
  const FADE_MS$1 = 1e3;
  function useSellTabTutorial({
    enabled,
    mode,
    boardLoading: boardLoading2,
    takeContractTargetId
  }) {
    const [phase, setPhase] = reactExports.useState("loading");
    const [backdropOpacity, setBackdropOpacity] = reactExports.useState(0);
    const dismissStarted = reactExports.useRef(false);
    const storageChecked = reactExports.useRef(false);
    const completeTutorial = reactExports.useCallback(() => {
      if (dismissStarted.current) return;
      dismissStarted.current = true;
      setPhase("dismissing");
      setBackdropOpacity(0);
      void markSellTabTutorialSeen();
    }, []);
    reactExports.useEffect(() => {
      if (storageChecked.current) return;
      storageChecked.current = true;
      let cancelled = false;
      void hasSeenSellTabTutorial().then((seen) => {
        if (cancelled) return;
        setPhase(seen || !enabled ? "done" : "sellTab");
      });
      return () => {
        cancelled = true;
      };
    }, []);
    const sellTabPhaseActive = phase === "sellTab";
    const takeContractPhaseActive = phase === "takeContract" && mode === "buying" && !boardLoading2 && takeContractTargetId !== null;
    const spotlightActive = enabled && (sellTabPhaseActive || takeContractPhaseActive || phase === "dismissing");
    reactExports.useEffect(() => {
      if (!spotlightActive || phase === "dismissing") return;
      const id2 = requestAnimationFrame(() => {
        requestAnimationFrame(() => setBackdropOpacity(1));
      });
      return () => cancelAnimationFrame(id2);
    }, [spotlightActive, phase, takeContractTargetId, boardLoading2]);
    reactExports.useEffect(() => {
      if (spotlightActive || phase === "loading" || phase === "done") return;
      setBackdropOpacity(0);
    }, [spotlightActive, phase]);
    reactExports.useEffect(() => {
      if (phase === "sellTab" && mode === "buying") {
        setPhase("takeContract");
      }
    }, [phase, mode]);
    reactExports.useEffect(() => {
      if (phase !== "takeContract" || mode !== "buying" || boardLoading2) return;
      if (takeContractTargetId === null) {
        completeTutorial();
      }
    }, [
      phase,
      mode,
      boardLoading2,
      takeContractTargetId,
      completeTutorial
    ]);
    const notifySellTabSelected = reactExports.useCallback(() => {
      if (phase !== "sellTab") return;
      setPhase("takeContract");
    }, [phase]);
    const notifyTakeContractSelected = reactExports.useCallback(() => {
      if (phase !== "takeContract") return;
      completeTutorial();
    }, [phase, completeTutorial]);
    const onBackdropTransitionEnd = reactExports.useCallback(
      (propertyName) => {
        if (propertyName !== "opacity" || phase !== "dismissing") return;
        setPhase("done");
      },
      [phase]
    );
    const showBackdrop = spotlightActive || enabled && phase === "dismissing";
    return {
      sellTabPhaseActive,
      takeContractPhaseActive,
      inTakeContractStep: phase === "takeContract",
      showBackdrop,
      backdropOpacity,
      fadeMs: FADE_MS$1,
      notifySellTabSelected,
      notifyTakeContractSelected,
      onBackdropTransitionEnd,
      sellTabTutorialBlocking: enabled && sellTabPhaseActive,
      takeContractTutorialBlocking: enabled && takeContractPhaseActive
    };
  }
  const STORAGE_KEY$4 = "sell_attacks_take_contract_intro_seen";
  async function hasSeenSellAttacksTutorial() {
    try {
      return await getPlatformRuntime().storage.get(STORAGE_KEY$4) === true;
    } catch {
      return false;
    }
  }
  async function markSellAttacksTutorialSeen() {
    try {
      await getPlatformRuntime().storage.set(STORAGE_KEY$4, true);
    } catch {
    }
  }
  const FADE_MS = 1e3;
  function useSellAttacksTakeContractTutorial({
    enabled,
    mode,
    boardLoading: boardLoading2,
    takeContractTargetId
  }) {
    const [phase, setPhase] = reactExports.useState("loading");
    const [backdropOpacity, setBackdropOpacity] = reactExports.useState(0);
    const dismissStarted = reactExports.useRef(false);
    const storageChecked = reactExports.useRef(false);
    reactExports.useEffect(() => {
      if (storageChecked.current) return;
      storageChecked.current = true;
      let cancelled = false;
      void hasSeenSellAttacksTutorial().then((seen) => {
        if (cancelled) return;
        setPhase(seen ? "done" : "idle");
      });
      return () => {
        cancelled = true;
      };
    }, []);
    const takeContractPhaseActive = enabled && phase === "takeContract" && mode === "buying" && !boardLoading2 && takeContractTargetId !== null;
    const spotlightActive = takeContractPhaseActive || phase === "dismissing";
    reactExports.useEffect(() => {
      if (phase === "idle" && enabled && mode === "buying" && !boardLoading2 && takeContractTargetId !== null) {
        setPhase("takeContract");
        void markSellAttacksTutorialSeen();
      }
    }, [phase, enabled, mode, boardLoading2, takeContractTargetId]);
    reactExports.useEffect(() => {
      if (!spotlightActive || phase === "dismissing") return;
      const id2 = requestAnimationFrame(() => {
        requestAnimationFrame(() => setBackdropOpacity(1));
      });
      return () => cancelAnimationFrame(id2);
    }, [spotlightActive, phase, takeContractTargetId, boardLoading2]);
    reactExports.useEffect(() => {
      if (spotlightActive || phase === "loading" || phase === "done") return;
      setBackdropOpacity(0);
    }, [spotlightActive, phase]);
    const completeTutorial = reactExports.useCallback(() => {
      if (dismissStarted.current) return;
      dismissStarted.current = true;
      setPhase("dismissing");
      setBackdropOpacity(0);
    }, []);
    reactExports.useEffect(() => {
      if (phase !== "takeContract") return;
      if (mode !== "buying") {
        setPhase("done");
        return;
      }
      if (!boardLoading2 && takeContractTargetId === null) {
        completeTutorial();
      }
    }, [phase, mode, boardLoading2, takeContractTargetId, completeTutorial]);
    const notifyTakeContractSelected = reactExports.useCallback(() => {
      if (phase !== "takeContract") return;
      completeTutorial();
    }, [phase, completeTutorial]);
    const onBackdropTransitionEnd = reactExports.useCallback(
      (propertyName) => {
        if (propertyName !== "opacity" || phase !== "dismissing") return;
        setPhase("done");
      },
      [phase]
    );
    return {
      takeContractPhaseActive,
      showBackdrop: spotlightActive,
      backdropOpacity,
      fadeMs: FADE_MS,
      notifyTakeContractSelected,
      onBackdropTransitionEnd,
      /** True while the spotlight wants the take-contract button ref attached. */
      takeContractTutorialActive: spotlightActive
    };
  }
  function useSellerSidebarTour({
    enabled,
    mode,
    topLossTargetId
  }) {
    const [phase, setPhase] = reactExports.useState("loading");
    const storageChecked = reactExports.useRef(false);
    const goMarked = reactExports.useRef(false);
    const takeMarked = reactExports.useRef(false);
    reactExports.useEffect(() => {
      if (storageChecked.current) return;
      storageChecked.current = true;
      let cancelled = false;
      void Promise.all([
        hasSeenSellerGoSellAttacks(),
        hasSeenSellerTakeContract()
      ]).then(([goSeen, takeSeen]) => {
        if (cancelled) return;
        if (goSeen) goMarked.current = true;
        if (takeSeen) takeMarked.current = true;
        setPhase(!goSeen ? "goSellAttacks" : !takeSeen ? "takeContract" : "done");
      });
      return () => {
        cancelled = true;
      };
    }, []);
    const advancePastGoSellAttacks = reactExports.useCallback(() => {
      if (!goMarked.current) {
        goMarked.current = true;
        void markSellerGoSellAttacksSeen();
      }
      setPhase(
        (prev) => prev === "goSellAttacks" ? takeMarked.current ? "done" : "takeContract" : prev
      );
    }, []);
    const goSellAttacksActive = enabled;
    const takeContractActive = enabled;
    reactExports.useEffect(() => {
    }, [phase, enabled, mode, advancePastGoSellAttacks]);
    reactExports.useEffect(() => {
    }, [goSellAttacksActive]);
    reactExports.useEffect(() => {
    }, [takeContractActive]);
    const notifySwitchedToSellAttacks = reactExports.useCallback(() => {
      if (phase === "goSellAttacks") advancePastGoSellAttacks();
    }, [phase, advancePastGoSellAttacks]);
    const notifyTakeContractSelected = reactExports.useCallback(() => {
      setPhase((prev) => prev === "takeContract" ? "done" : prev);
    }, []);
    const notifySignedIn = reactExports.useCallback(() => {
      if (!takeMarked.current) return;
      setPhase((prev) => prev === "done" ? "takeContract" : prev);
    }, []);
    return {
      goSellAttacksActive,
      takeContractActive,
      notifySwitchedToSellAttacks,
      notifyTakeContractSelected,
      notifySignedIn
    };
  }
  function isTouchPrimaryInput() {
    return window.matchMedia("(hover: none), (pointer: coarse)").matches;
  }
  function takeContractRowHint() {
    return isTouchPrimaryInput() ? TAKE_CONTRACT_BUTTON_LABEL : `hover for ${TAKE_CONTRACT_BUTTON_LABEL}`;
  }
  const LayoutGroupContext = reactExports.createContext({});
  function useConstant(init) {
    const ref = reactExports.useRef(null);
    if (ref.current === null) {
      ref.current = init();
    }
    return ref.current;
  }
  const isBrowser$1 = typeof window !== "undefined";
  const useIsomorphicLayoutEffect = isBrowser$1 ? reactExports.useLayoutEffect : reactExports.useEffect;
  const PresenceContext = /* @__PURE__ */ reactExports.createContext(null);
  function addUniqueItem(arr, item) {
    if (arr.indexOf(item) === -1)
      arr.push(item);
  }
  function removeItem(arr, item) {
    const index = arr.indexOf(item);
    if (index > -1)
      arr.splice(index, 1);
  }
  const clamp = (min, max, v) => {
    if (v > max)
      return max;
    if (v < min)
      return min;
    return v;
  };
  function formatErrorMessage(message, errorCode) {
    return errorCode ? `${message}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${errorCode}` : message;
  }
  let warning = () => {
  };
  let invariant = () => {
  };
  if (typeof process !== "undefined" && ((_a = process.env) == null ? void 0 : _a.NODE_ENV) !== "production") {
    warning = (check, message, errorCode) => {
      if (!check && typeof console !== "undefined") {
        console.warn(formatErrorMessage(message, errorCode));
      }
    };
    invariant = (check, message, errorCode) => {
      if (!check) {
        throw new Error(formatErrorMessage(message, errorCode));
      }
    };
  }
  const MotionGlobalConfig = {};
  const isNumericalString = (v) => /^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(v);
  function isObject(value) {
    return typeof value === "object" && value !== null;
  }
  const isZeroValueString = (v) => /^0[^.\s]+$/u.test(v);
  // @__NO_SIDE_EFFECTS__
  function memo(callback) {
    let result;
    return () => {
      if (result === void 0)
        result = callback();
      return result;
    };
  }
  const noop = /* @__NO_SIDE_EFFECTS__ */ (any) => any;
  const combineFunctions = (a, b) => (v) => b(a(v));
  const pipe = (...transformers) => transformers.reduce(combineFunctions);
  const progress$1 = /* @__NO_SIDE_EFFECTS__ */ (from, to, value) => {
    const toFromDifference = to - from;
    return toFromDifference === 0 ? 1 : (value - from) / toFromDifference;
  };
  class SubscriptionManager {
    constructor() {
      this.subscriptions = [];
    }
    add(handler) {
      addUniqueItem(this.subscriptions, handler);
      return () => removeItem(this.subscriptions, handler);
    }
    notify(a, b, c) {
      const numSubscriptions = this.subscriptions.length;
      if (!numSubscriptions)
        return;
      if (numSubscriptions === 1) {
        this.subscriptions[0](a, b, c);
      } else {
        for (let i = 0; i < numSubscriptions; i++) {
          const handler = this.subscriptions[i];
          handler && handler(a, b, c);
        }
      }
    }
    getSize() {
      return this.subscriptions.length;
    }
    clear() {
      this.subscriptions.length = 0;
    }
  }
  const secondsToMilliseconds = /* @__NO_SIDE_EFFECTS__ */ (seconds) => seconds * 1e3;
  const millisecondsToSeconds = /* @__NO_SIDE_EFFECTS__ */ (milliseconds) => milliseconds / 1e3;
  function velocityPerSecond(velocity, frameDuration) {
    return frameDuration ? velocity * (1e3 / frameDuration) : 0;
  }
  const calcBezier = (t, a1, a2) => (((1 - 3 * a2 + 3 * a1) * t + (3 * a2 - 6 * a1)) * t + 3 * a1) * t;
  const subdivisionPrecision = 1e-7;
  const subdivisionMaxIterations = 12;
  function binarySubdivide(x, lowerBound, upperBound, mX1, mX2) {
    let currentX;
    let currentT;
    let i = 0;
    do {
      currentT = lowerBound + (upperBound - lowerBound) / 2;
      currentX = calcBezier(currentT, mX1, mX2) - x;
      if (currentX > 0) {
        upperBound = currentT;
      } else {
        lowerBound = currentT;
      }
    } while (Math.abs(currentX) > subdivisionPrecision && ++i < subdivisionMaxIterations);
    return currentT;
  }
  function cubicBezier(mX1, mY1, mX2, mY2) {
    if (mX1 === mY1 && mX2 === mY2)
      return noop;
    const getTForX = (aX) => binarySubdivide(aX, 0, 1, mX1, mX2);
    return (t) => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2);
  }
  const mirrorEasing = (easing) => (p) => p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2;
  const reverseEasing = (easing) => (p) => 1 - easing(1 - p);
  const backOut = /* @__PURE__ */ cubicBezier(0.33, 1.53, 0.69, 0.99);
  const backIn = /* @__PURE__ */ reverseEasing(backOut);
  const backInOut = /* @__PURE__ */ mirrorEasing(backIn);
  const anticipate = (p) => p >= 1 ? 1 : (p *= 2) < 1 ? 0.5 * backIn(p) : 0.5 * (2 - Math.pow(2, -10 * (p - 1)));
  const circIn = (p) => 1 - Math.sin(Math.acos(p));
  const circOut = reverseEasing(circIn);
  const circInOut = mirrorEasing(circIn);
  const easeIn = /* @__PURE__ */ cubicBezier(0.42, 0, 1, 1);
  const easeOut = /* @__PURE__ */ cubicBezier(0, 0, 0.58, 1);
  const easeInOut = /* @__PURE__ */ cubicBezier(0.42, 0, 0.58, 1);
  const isEasingArray = (ease2) => {
    return Array.isArray(ease2) && typeof ease2[0] !== "number";
  };
  const isBezierDefinition = (easing) => Array.isArray(easing) && typeof easing[0] === "number";
  const easingLookup = {
    linear: noop,
    easeIn,
    easeInOut,
    easeOut,
    circIn,
    circInOut,
    circOut,
    backIn,
    backInOut,
    backOut,
    anticipate
  };
  const isValidEasing = (easing) => {
    return typeof easing === "string";
  };
  const easingDefinitionToFunction = (definition) => {
    if (isBezierDefinition(definition)) {
      invariant(definition.length === 4, `Cubic bezier arrays must contain four numerical values.`, "cubic-bezier-length");
      const [x1, y1, x2, y2] = definition;
      return cubicBezier(x1, y1, x2, y2);
    } else if (isValidEasing(definition)) {
      invariant(easingLookup[definition] !== void 0, `Invalid easing type '${definition}'`, "invalid-easing-type");
      return easingLookup[definition];
    }
    return definition;
  };
  const stepsOrder = [
    "setup",
    // Compute
    "read",
    // Read
    "resolveKeyframes",
    // Write/Read/Write/Read
    "preUpdate",
    // Compute
    "update",
    // Compute
    "preRender",
    // Compute
    "render",
    // Write
    "postRender"
    // Compute
  ];
  function createRenderStep(runNextFrame, stepName) {
    let thisFrame = /* @__PURE__ */ new Set();
    let nextFrame = /* @__PURE__ */ new Set();
    let isProcessing = false;
    let flushNextFrame = false;
    const toKeepAlive = /* @__PURE__ */ new WeakSet();
    let latestFrameData = {
      delta: 0,
      timestamp: 0,
      isProcessing: false
    };
    function triggerCallback(callback) {
      if (toKeepAlive.has(callback)) {
        step2.schedule(callback);
        runNextFrame();
      }
      callback(latestFrameData);
    }
    const step2 = {
      /**
       * Schedule a process to run on the next frame.
       */
      schedule: (callback, keepAlive = false, immediate = false) => {
        const addToCurrentFrame = immediate && isProcessing;
        const queue = addToCurrentFrame ? thisFrame : nextFrame;
        if (keepAlive)
          toKeepAlive.add(callback);
        queue.add(callback);
        return callback;
      },
      /**
       * Cancel the provided callback from running on the next frame.
       */
      cancel: (callback) => {
        nextFrame.delete(callback);
        toKeepAlive.delete(callback);
      },
      /**
       * Execute all schedule callbacks.
       */
      process: (frameData2) => {
        latestFrameData = frameData2;
        if (isProcessing) {
          flushNextFrame = true;
          return;
        }
        isProcessing = true;
        const prevFrame = thisFrame;
        thisFrame = nextFrame;
        nextFrame = prevFrame;
        thisFrame.forEach(triggerCallback);
        thisFrame.clear();
        isProcessing = false;
        if (flushNextFrame) {
          flushNextFrame = false;
          step2.process(frameData2);
        }
      }
    };
    return step2;
  }
  const maxElapsed = 40;
  function createRenderBatcher(scheduleNextBatch, allowKeepAlive) {
    let runNextFrame = false;
    let useDefaultElapsed = true;
    const state = {
      delta: 0,
      timestamp: 0,
      isProcessing: false
    };
    const flagRunNextFrame = () => runNextFrame = true;
    const steps = stepsOrder.reduce((acc, key) => {
      acc[key] = createRenderStep(flagRunNextFrame);
      return acc;
    }, {});
    const { setup, read, resolveKeyframes, preUpdate, update, preRender, render, postRender } = steps;
    const processBatch = () => {
      const useManualTiming = MotionGlobalConfig.useManualTiming;
      const timestamp = useManualTiming ? state.timestamp : performance.now();
      runNextFrame = false;
      if (!useManualTiming) {
        state.delta = useDefaultElapsed ? 1e3 / 60 : Math.max(Math.min(timestamp - state.timestamp, maxElapsed), 1);
      }
      state.timestamp = timestamp;
      state.isProcessing = true;
      setup.process(state);
      read.process(state);
      resolveKeyframes.process(state);
      preUpdate.process(state);
      update.process(state);
      preRender.process(state);
      render.process(state);
      postRender.process(state);
      state.isProcessing = false;
      if (runNextFrame && allowKeepAlive) {
        useDefaultElapsed = false;
        scheduleNextBatch(processBatch);
      }
    };
    const wake = () => {
      runNextFrame = true;
      useDefaultElapsed = true;
      if (!state.isProcessing) {
        scheduleNextBatch(processBatch);
      }
    };
    const schedule = stepsOrder.reduce((acc, key) => {
      const step2 = steps[key];
      acc[key] = (process2, keepAlive = false, immediate = false) => {
        if (!runNextFrame)
          wake();
        return step2.schedule(process2, keepAlive, immediate);
      };
      return acc;
    }, {});
    const cancel2 = (process2) => {
      for (let i = 0; i < stepsOrder.length; i++) {
        steps[stepsOrder[i]].cancel(process2);
      }
    };
    return { schedule, cancel: cancel2, state, steps };
  }
  const { schedule: frame, cancel: cancelFrame, state: frameData, steps: frameSteps } = /* @__PURE__ */ createRenderBatcher(typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : noop, true);
  let now;
  function clearTime() {
    now = void 0;
  }
  const time = {
    now: () => {
      if (now === void 0) {
        time.set(frameData.isProcessing || MotionGlobalConfig.useManualTiming ? frameData.timestamp : performance.now());
      }
      return now;
    },
    set: (newTime) => {
      now = newTime;
      queueMicrotask(clearTime);
    }
  };
  const checkStringStartsWith = (token) => (key) => typeof key === "string" && key.startsWith(token);
  const isCSSVariableName = /* @__PURE__ */ checkStringStartsWith("--");
  const startsAsVariableToken = /* @__PURE__ */ checkStringStartsWith("var(--");
  const isCSSVariableToken = (value) => {
    const startsWithToken = startsAsVariableToken(value);
    if (!startsWithToken)
      return false;
    return singleCssVariableRegex.test(value.split("/*")[0].trim());
  };
  const singleCssVariableRegex = /var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;
  function containsCSSVariable(value) {
    if (typeof value !== "string")
      return false;
    return value.split("/*")[0].includes("var(--");
  }
  const number = {
    test: (v) => typeof v === "number",
    parse: parseFloat,
    transform: (v) => v
  };
  const alpha = {
    ...number,
    transform: (v) => clamp(0, 1, v)
  };
  const scale = {
    ...number,
    default: 1
  };
  const sanitize = (v) => Math.round(v * 1e5) / 1e5;
  const floatRegex = /-?(?:\d+(?:\.\d+)?|\.\d+)/gu;
  function isNullish(v) {
    return v == null;
  }
  const singleColorRegex = /^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu;
  const isColorString = (type, testProp) => (v) => {
    return Boolean(typeof v === "string" && singleColorRegex.test(v) && v.startsWith(type) || testProp && !isNullish(v) && Object.prototype.hasOwnProperty.call(v, testProp));
  };
  const splitColor = (aName, bName, cName) => (v) => {
    if (typeof v !== "string")
      return v;
    const [a, b, c, alpha2] = v.match(floatRegex);
    return {
      [aName]: parseFloat(a),
      [bName]: parseFloat(b),
      [cName]: parseFloat(c),
      alpha: alpha2 !== void 0 ? parseFloat(alpha2) : 1
    };
  };
  const clampRgbUnit = (v) => clamp(0, 255, v);
  const rgbUnit = {
    ...number,
    transform: (v) => Math.round(clampRgbUnit(v))
  };
  const rgba = {
    test: /* @__PURE__ */ isColorString("rgb", "red"),
    parse: /* @__PURE__ */ splitColor("red", "green", "blue"),
    transform: ({ red, green, blue, alpha: alpha$1 = 1 }) => "rgba(" + rgbUnit.transform(red) + ", " + rgbUnit.transform(green) + ", " + rgbUnit.transform(blue) + ", " + sanitize(alpha.transform(alpha$1)) + ")"
  };
  function parseHex(v) {
    let r = "";
    let g = "";
    let b = "";
    let a = "";
    if (v.length > 5) {
      r = v.substring(1, 3);
      g = v.substring(3, 5);
      b = v.substring(5, 7);
      a = v.substring(7, 9);
    } else {
      r = v.substring(1, 2);
      g = v.substring(2, 3);
      b = v.substring(3, 4);
      a = v.substring(4, 5);
      r += r;
      g += g;
      b += b;
      a += a;
    }
    return {
      red: parseInt(r, 16),
      green: parseInt(g, 16),
      blue: parseInt(b, 16),
      alpha: a ? parseInt(a, 16) / 255 : 1
    };
  }
  const hex = {
    test: /* @__PURE__ */ isColorString("#"),
    parse: parseHex,
    transform: rgba.transform
  };
  const createUnitType = /* @__NO_SIDE_EFFECTS__ */ (unit) => ({
    test: (v) => typeof v === "string" && v.endsWith(unit) && v.split(" ").length === 1,
    parse: parseFloat,
    transform: (v) => `${v}${unit}`
  });
  const degrees = /* @__PURE__ */ createUnitType("deg");
  const percent = /* @__PURE__ */ createUnitType("%");
  const px = /* @__PURE__ */ createUnitType("px");
  const vh = /* @__PURE__ */ createUnitType("vh");
  const vw = /* @__PURE__ */ createUnitType("vw");
  const progressPercentage = /* @__PURE__ */ (() => ({
    ...percent,
    parse: (v) => percent.parse(v) / 100,
    transform: (v) => percent.transform(v * 100)
  }))();
  const hsla = {
    test: /* @__PURE__ */ isColorString("hsl", "hue"),
    parse: /* @__PURE__ */ splitColor("hue", "saturation", "lightness"),
    transform: ({ hue, saturation, lightness, alpha: alpha$1 = 1 }) => {
      return "hsla(" + Math.round(hue) + ", " + percent.transform(sanitize(saturation)) + ", " + percent.transform(sanitize(lightness)) + ", " + sanitize(alpha.transform(alpha$1)) + ")";
    }
  };
  const color = {
    test: (v) => rgba.test(v) || hex.test(v) || hsla.test(v),
    parse: (v) => {
      if (rgba.test(v)) {
        return rgba.parse(v);
      } else if (hsla.test(v)) {
        return hsla.parse(v);
      } else {
        return hex.parse(v);
      }
    },
    transform: (v) => {
      return typeof v === "string" ? v : v.hasOwnProperty("red") ? rgba.transform(v) : hsla.transform(v);
    },
    getAnimatableNone: (v) => {
      const parsed = color.parse(v);
      parsed.alpha = 0;
      return color.transform(parsed);
    }
  };
  const colorRegex = /(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;
  function test(v) {
    var _a2, _b;
    return isNaN(v) && typeof v === "string" && (((_a2 = v.match(floatRegex)) == null ? void 0 : _a2.length) || 0) + (((_b = v.match(colorRegex)) == null ? void 0 : _b.length) || 0) > 0;
  }
  const NUMBER_TOKEN = "number";
  const COLOR_TOKEN = "color";
  const VAR_TOKEN = "var";
  const VAR_FUNCTION_TOKEN = "var(";
  const SPLIT_TOKEN = "${}";
  const complexRegex = /var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;
  function analyseComplexValue(value) {
    const originalValue = value.toString();
    const values = [];
    const indexes = {
      color: [],
      number: [],
      var: []
    };
    const types = [];
    let i = 0;
    const tokenised = originalValue.replace(complexRegex, (parsedValue) => {
      if (color.test(parsedValue)) {
        indexes.color.push(i);
        types.push(COLOR_TOKEN);
        values.push(color.parse(parsedValue));
      } else if (parsedValue.startsWith(VAR_FUNCTION_TOKEN)) {
        indexes.var.push(i);
        types.push(VAR_TOKEN);
        values.push(parsedValue);
      } else {
        indexes.number.push(i);
        types.push(NUMBER_TOKEN);
        values.push(parseFloat(parsedValue));
      }
      ++i;
      return SPLIT_TOKEN;
    });
    const split = tokenised.split(SPLIT_TOKEN);
    return { values, split, indexes, types };
  }
  function parseComplexValue(v) {
    return analyseComplexValue(v).values;
  }
  function buildTransformer({ split, types }) {
    const numSections = split.length;
    return (v) => {
      let output = "";
      for (let i = 0; i < numSections; i++) {
        output += split[i];
        if (v[i] !== void 0) {
          const type = types[i];
          if (type === NUMBER_TOKEN) {
            output += sanitize(v[i]);
          } else if (type === COLOR_TOKEN) {
            output += color.transform(v[i]);
          } else {
            output += v[i];
          }
        }
      }
      return output;
    };
  }
  function createTransformer(source) {
    return buildTransformer(analyseComplexValue(source));
  }
  const convertNumbersToZero = (v) => typeof v === "number" ? 0 : color.test(v) ? color.getAnimatableNone(v) : v;
  const convertToZero = (value, splitBefore) => {
    if (typeof value === "number") {
      return (splitBefore == null ? void 0 : splitBefore.trim().endsWith("/")) ? value : 0;
    }
    return convertNumbersToZero(value);
  };
  function getAnimatableNone$1(v) {
    const info = analyseComplexValue(v);
    const transformer = buildTransformer(info);
    return transformer(info.values.map((value, i) => convertToZero(value, info.split[i])));
  }
  const complex = {
    test,
    parse: parseComplexValue,
    createTransformer,
    getAnimatableNone: getAnimatableNone$1
  };
  function hueToRgb(p, q, t) {
    if (t < 0)
      t += 1;
    if (t > 1)
      t -= 1;
    if (t < 1 / 6)
      return p + (q - p) * 6 * t;
    if (t < 1 / 2)
      return q;
    if (t < 2 / 3)
      return p + (q - p) * (2 / 3 - t) * 6;
    return p;
  }
  function hslaToRgba({ hue, saturation, lightness, alpha: alpha2 }) {
    hue /= 360;
    saturation /= 100;
    lightness /= 100;
    let red = 0;
    let green = 0;
    let blue = 0;
    if (!saturation) {
      red = green = blue = lightness;
    } else {
      const q = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation;
      const p = 2 * lightness - q;
      red = hueToRgb(p, q, hue + 1 / 3);
      green = hueToRgb(p, q, hue);
      blue = hueToRgb(p, q, hue - 1 / 3);
    }
    return {
      red: Math.round(red * 255),
      green: Math.round(green * 255),
      blue: Math.round(blue * 255),
      alpha: alpha2
    };
  }
  function mixImmediate(a, b) {
    return (p) => p > 0 ? b : a;
  }
  const mixNumber$1 = (from, to, progress2) => {
    return from + (to - from) * progress2;
  };
  const mixLinearColor = (from, to, v) => {
    const fromExpo = from * from;
    const expo = v * (to * to - fromExpo) + fromExpo;
    return expo < 0 ? 0 : Math.sqrt(expo);
  };
  const colorTypes = [hex, rgba, hsla];
  const getColorType = (v) => colorTypes.find((type) => type.test(v));
  function asRGBA(color2) {
    const type = getColorType(color2);
    warning(Boolean(type), `'${color2}' is not an animatable color. Use the equivalent color code instead.`, "color-not-animatable");
    if (!Boolean(type))
      return false;
    let model = type.parse(color2);
    if (type === hsla) {
      model = hslaToRgba(model);
    }
    return model;
  }
  const mixColor = (from, to) => {
    const fromRGBA = asRGBA(from);
    const toRGBA = asRGBA(to);
    if (!fromRGBA || !toRGBA) {
      return mixImmediate(from, to);
    }
    const blended = { ...fromRGBA };
    return (v) => {
      blended.red = mixLinearColor(fromRGBA.red, toRGBA.red, v);
      blended.green = mixLinearColor(fromRGBA.green, toRGBA.green, v);
      blended.blue = mixLinearColor(fromRGBA.blue, toRGBA.blue, v);
      blended.alpha = mixNumber$1(fromRGBA.alpha, toRGBA.alpha, v);
      return rgba.transform(blended);
    };
  };
  const invisibleValues = /* @__PURE__ */ new Set(["none", "hidden"]);
  function mixVisibility(origin, target2) {
    if (invisibleValues.has(origin)) {
      return (p) => p <= 0 ? origin : target2;
    } else {
      return (p) => p >= 1 ? target2 : origin;
    }
  }
  function mixNumber(a, b) {
    return (p) => mixNumber$1(a, b, p);
  }
  function getMixer(a) {
    if (typeof a === "number") {
      return mixNumber;
    } else if (typeof a === "string") {
      return isCSSVariableToken(a) ? mixImmediate : color.test(a) ? mixColor : mixComplex;
    } else if (Array.isArray(a)) {
      return mixArray;
    } else if (typeof a === "object") {
      return color.test(a) ? mixColor : mixObject;
    }
    return mixImmediate;
  }
  function mixArray(a, b) {
    const output = [...a];
    const numValues = output.length;
    const blendValue = a.map((v, i) => getMixer(v)(v, b[i]));
    return (p) => {
      for (let i = 0; i < numValues; i++) {
        output[i] = blendValue[i](p);
      }
      return output;
    };
  }
  function mixObject(a, b) {
    const output = { ...a, ...b };
    const blendValue = {};
    for (const key in output) {
      if (a[key] !== void 0 && b[key] !== void 0) {
        blendValue[key] = getMixer(a[key])(a[key], b[key]);
      }
    }
    return (v) => {
      for (const key in blendValue) {
        output[key] = blendValue[key](v);
      }
      return output;
    };
  }
  function matchOrder(origin, target2) {
    const orderedOrigin = [];
    const pointers = { color: 0, var: 0, number: 0 };
    for (let i = 0; i < target2.values.length; i++) {
      const type = target2.types[i];
      const originIndex = origin.indexes[type][pointers[type]];
      const originValue = origin.values[originIndex] ?? 0;
      orderedOrigin[i] = originValue;
      pointers[type]++;
    }
    return orderedOrigin;
  }
  const mixComplex = (origin, target2) => {
    const template = complex.createTransformer(target2);
    const originStats = analyseComplexValue(origin);
    const targetStats = analyseComplexValue(target2);
    const canInterpolate = originStats.indexes.var.length === targetStats.indexes.var.length && originStats.indexes.color.length === targetStats.indexes.color.length && originStats.indexes.number.length >= targetStats.indexes.number.length;
    if (canInterpolate) {
      if (invisibleValues.has(origin) && !targetStats.values.length || invisibleValues.has(target2) && !originStats.values.length) {
        return mixVisibility(origin, target2);
      }
      return pipe(mixArray(matchOrder(originStats, targetStats), targetStats.values), template);
    } else {
      warning(true, `Complex values '${origin}' and '${target2}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`, "complex-values-different");
      return mixImmediate(origin, target2);
    }
  };
  function mix(from, to, p) {
    if (typeof from === "number" && typeof to === "number" && typeof p === "number") {
      return mixNumber$1(from, to, p);
    }
    const mixer = getMixer(from);
    return mixer(from, to);
  }
  const frameloopDriver = (update) => {
    const passTimestamp = ({ timestamp }) => update(timestamp);
    return {
      start: (keepAlive = true) => frame.update(passTimestamp, keepAlive),
      stop: () => cancelFrame(passTimestamp),
      /**
       * If we're processing this frame we can use the
       * framelocked timestamp to keep things in sync.
       */
      now: () => frameData.isProcessing ? frameData.timestamp : time.now()
    };
  };
  const generateLinearEasing = (easing, duration, resolution = 10) => {
    let points = "";
    const numPoints = Math.max(Math.round(duration / resolution), 2);
    for (let i = 0; i < numPoints; i++) {
      points += Math.round(easing(i / (numPoints - 1)) * 1e4) / 1e4 + ", ";
    }
    return `linear(${points.substring(0, points.length - 2)})`;
  };
  const maxGeneratorDuration = 2e4;
  function calcGeneratorDuration(generator) {
    let duration = 0;
    const timeStep = 50;
    let state = generator.next(duration);
    while (!state.done && duration < maxGeneratorDuration) {
      duration += timeStep;
      state = generator.next(duration);
    }
    return duration >= maxGeneratorDuration ? Infinity : duration;
  }
  function createGeneratorEasing(options, scale2 = 100, createGenerator) {
    const generator = createGenerator({ ...options, keyframes: [0, scale2] });
    const duration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration);
    return {
      type: "keyframes",
      ease: (progress2) => {
        return generator.next(duration * progress2).value / scale2;
      },
      duration: /* @__PURE__ */ millisecondsToSeconds(duration)
    };
  }
  const springDefaults = {
    // Default spring physics
    stiffness: 100,
    damping: 10,
    mass: 1,
    velocity: 0,
    // Default duration/bounce-based options
    duration: 800,
    // in ms
    bounce: 0.3,
    visualDuration: 0.3,
    // in seconds
    // Rest thresholds
    restSpeed: {
      granular: 0.01,
      default: 2
    },
    restDelta: {
      granular: 5e-3,
      default: 0.5
    },
    // Limits
    minDuration: 0.01,
    // in seconds
    maxDuration: 10,
    // in seconds
    minDamping: 0.05,
    maxDamping: 1
  };
  function calcAngularFreq(undampedFreq, dampingRatio) {
    return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio);
  }
  const rootIterations = 12;
  function approximateRoot(envelope, derivative, initialGuess) {
    let result = initialGuess;
    for (let i = 1; i < rootIterations; i++) {
      result = result - envelope(result) / derivative(result);
    }
    return result;
  }
  const safeMin = 1e-3;
  function findSpring({ duration = springDefaults.duration, bounce = springDefaults.bounce, velocity = springDefaults.velocity, mass = springDefaults.mass }) {
    let envelope;
    let derivative;
    warning(duration <= /* @__PURE__ */ secondsToMilliseconds(springDefaults.maxDuration), "Spring duration must be 10 seconds or less", "spring-duration-limit");
    let dampingRatio = 1 - bounce;
    dampingRatio = clamp(springDefaults.minDamping, springDefaults.maxDamping, dampingRatio);
    duration = clamp(springDefaults.minDuration, springDefaults.maxDuration, /* @__PURE__ */ millisecondsToSeconds(duration));
    if (dampingRatio < 1) {
      envelope = (undampedFreq2) => {
        const exponentialDecay = undampedFreq2 * dampingRatio;
        const delta = exponentialDecay * duration;
        const a = exponentialDecay - velocity;
        const b = calcAngularFreq(undampedFreq2, dampingRatio);
        const c = Math.exp(-delta);
        return safeMin - a / b * c;
      };
      derivative = (undampedFreq2) => {
        const exponentialDecay = undampedFreq2 * dampingRatio;
        const delta = exponentialDecay * duration;
        const d = delta * velocity + velocity;
        const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq2, 2) * duration;
        const f = Math.exp(-delta);
        const g = calcAngularFreq(Math.pow(undampedFreq2, 2), dampingRatio);
        const factor = -envelope(undampedFreq2) + safeMin > 0 ? -1 : 1;
        return factor * ((d - e) * f) / g;
      };
    } else {
      envelope = (undampedFreq2) => {
        const a = Math.exp(-undampedFreq2 * duration);
        const b = (undampedFreq2 - velocity) * duration + 1;
        return -safeMin + a * b;
      };
      derivative = (undampedFreq2) => {
        const a = Math.exp(-undampedFreq2 * duration);
        const b = (velocity - undampedFreq2) * (duration * duration);
        return a * b;
      };
    }
    const initialGuess = 5 / duration;
    const undampedFreq = approximateRoot(envelope, derivative, initialGuess);
    duration = /* @__PURE__ */ secondsToMilliseconds(duration);
    if (isNaN(undampedFreq)) {
      return {
        stiffness: springDefaults.stiffness,
        damping: springDefaults.damping,
        duration
      };
    } else {
      const stiffness = Math.pow(undampedFreq, 2) * mass;
      return {
        stiffness,
        damping: dampingRatio * 2 * Math.sqrt(mass * stiffness),
        duration
      };
    }
  }
  const durationKeys = ["duration", "bounce"];
  const physicsKeys = ["stiffness", "damping", "mass"];
  function isSpringType(options, keys) {
    return keys.some((key) => options[key] !== void 0);
  }
  function getSpringOptions(options) {
    let springOptions = {
      velocity: springDefaults.velocity,
      stiffness: springDefaults.stiffness,
      damping: springDefaults.damping,
      mass: springDefaults.mass,
      isResolvedFromDuration: false,
      ...options
    };
    if (!isSpringType(options, physicsKeys) && isSpringType(options, durationKeys)) {
      springOptions.velocity = 0;
      if (options.visualDuration) {
        const visualDuration = options.visualDuration;
        const root2 = 2 * Math.PI / (visualDuration * 1.2);
        const stiffness = root2 * root2;
        const damping = 2 * clamp(0.05, 1, 1 - (options.bounce || 0)) * Math.sqrt(stiffness);
        springOptions = {
          ...springOptions,
          mass: springDefaults.mass,
          stiffness,
          damping
        };
      } else {
        const derived = findSpring({ ...options, velocity: 0 });
        springOptions = {
          ...springOptions,
          ...derived,
          mass: springDefaults.mass
        };
        springOptions.isResolvedFromDuration = true;
      }
    }
    return springOptions;
  }
  function spring(optionsOrVisualDuration = springDefaults.visualDuration, bounce = springDefaults.bounce) {
    const options = typeof optionsOrVisualDuration !== "object" ? {
      visualDuration: optionsOrVisualDuration,
      keyframes: [0, 1],
      bounce
    } : optionsOrVisualDuration;
    let { restSpeed, restDelta } = options;
    const origin = options.keyframes[0];
    const target2 = options.keyframes[options.keyframes.length - 1];
    const state = { done: false, value: origin };
    const { stiffness, damping, mass, duration, velocity, isResolvedFromDuration } = getSpringOptions({
      ...options,
      velocity: -/* @__PURE__ */ millisecondsToSeconds(options.velocity || 0)
    });
    const initialVelocity = velocity || 0;
    const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass));
    const initialDelta = target2 - origin;
    const undampedAngularFreq = /* @__PURE__ */ millisecondsToSeconds(Math.sqrt(stiffness / mass));
    const isGranularScale = Math.abs(initialDelta) < 5;
    restSpeed || (restSpeed = isGranularScale ? springDefaults.restSpeed.granular : springDefaults.restSpeed.default);
    restDelta || (restDelta = isGranularScale ? springDefaults.restDelta.granular : springDefaults.restDelta.default);
    let resolveSpring;
    let resolveVelocity;
    let angularFreq;
    let A;
    let sinCoeff;
    let cosCoeff;
    if (dampingRatio < 1) {
      angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio);
      A = (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq;
      resolveSpring = (t) => {
        const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
        return target2 - envelope * (A * Math.sin(angularFreq * t) + initialDelta * Math.cos(angularFreq * t));
      };
      sinCoeff = dampingRatio * undampedAngularFreq * A + initialDelta * angularFreq;
      cosCoeff = dampingRatio * undampedAngularFreq * initialDelta - A * angularFreq;
      resolveVelocity = (t) => {
        const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
        return envelope * (sinCoeff * Math.sin(angularFreq * t) + cosCoeff * Math.cos(angularFreq * t));
      };
    } else if (dampingRatio === 1) {
      resolveSpring = (t) => target2 - Math.exp(-undampedAngularFreq * t) * (initialDelta + (initialVelocity + undampedAngularFreq * initialDelta) * t);
      const C = initialVelocity + undampedAngularFreq * initialDelta;
      resolveVelocity = (t) => Math.exp(-undampedAngularFreq * t) * (undampedAngularFreq * C * t - initialVelocity);
    } else {
      const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1);
      resolveSpring = (t) => {
        const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
        const freqForT = Math.min(dampedAngularFreq * t, 300);
        return target2 - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) * Math.sinh(freqForT) + dampedAngularFreq * initialDelta * Math.cosh(freqForT)) / dampedAngularFreq;
      };
      const P = (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / dampedAngularFreq;
      const sinhCoeff = dampingRatio * undampedAngularFreq * P - initialDelta * dampedAngularFreq;
      const coshCoeff = dampingRatio * undampedAngularFreq * initialDelta - P * dampedAngularFreq;
      resolveVelocity = (t) => {
        const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
        const freqForT = Math.min(dampedAngularFreq * t, 300);
        return envelope * (sinhCoeff * Math.sinh(freqForT) + coshCoeff * Math.cosh(freqForT));
      };
    }
    const generator = {
      calculatedDuration: isResolvedFromDuration ? duration || null : null,
      velocity: (t) => /* @__PURE__ */ secondsToMilliseconds(resolveVelocity(t)),
      next: (t) => {
        if (!isResolvedFromDuration && dampingRatio < 1) {
          const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t);
          const sin = Math.sin(angularFreq * t);
          const cos = Math.cos(angularFreq * t);
          const current2 = target2 - envelope * (A * sin + initialDelta * cos);
          const currentVelocity = /* @__PURE__ */ secondsToMilliseconds(envelope * (sinCoeff * sin + cosCoeff * cos));
          state.done = Math.abs(currentVelocity) <= restSpeed && Math.abs(target2 - current2) <= restDelta;
          state.value = state.done ? target2 : current2;
          return state;
        }
        const current = resolveSpring(t);
        if (!isResolvedFromDuration) {
          const currentVelocity = /* @__PURE__ */ secondsToMilliseconds(resolveVelocity(t));
          state.done = Math.abs(currentVelocity) <= restSpeed && Math.abs(target2 - current) <= restDelta;
        } else {
          state.done = t >= duration;
        }
        state.value = state.done ? target2 : current;
        return state;
      },
      toString: () => {
        const calculatedDuration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration);
        const easing = generateLinearEasing((progress2) => generator.next(calculatedDuration * progress2).value, calculatedDuration, 30);
        return calculatedDuration + "ms " + easing;
      },
      toTransition: () => {
      }
    };
    return generator;
  }
  spring.applyToOptions = (options) => {
    const generatorOptions = createGeneratorEasing(options, 100, spring);
    options.ease = generatorOptions.ease;
    options.duration = /* @__PURE__ */ secondsToMilliseconds(generatorOptions.duration);
    options.type = "keyframes";
    return options;
  };
  const velocitySampleDuration = 5;
  function getGeneratorVelocity(resolveValue, t, current) {
    const prevT = Math.max(t - velocitySampleDuration, 0);
    return velocityPerSecond(current - resolveValue(prevT), t - prevT);
  }
  function inertia({ keyframes: keyframes2, velocity = 0, power = 0.8, timeConstant = 325, bounceDamping = 10, bounceStiffness = 500, modifyTarget, min, max, restDelta = 0.5, restSpeed }) {
    const origin = keyframes2[0];
    const state = {
      done: false,
      value: origin
    };
    const isOutOfBounds = (v) => min !== void 0 && v < min || max !== void 0 && v > max;
    const nearestBoundary = (v) => {
      if (min === void 0)
        return max;
      if (max === void 0)
        return min;
      return Math.abs(min - v) < Math.abs(max - v) ? min : max;
    };
    let amplitude = power * velocity;
    const ideal = origin + amplitude;
    const target2 = modifyTarget === void 0 ? ideal : modifyTarget(ideal);
    if (target2 !== ideal)
      amplitude = target2 - origin;
    const calcDelta = (t) => -amplitude * Math.exp(-t / timeConstant);
    const calcLatest = (t) => target2 + calcDelta(t);
    const applyFriction = (t) => {
      const delta = calcDelta(t);
      const latest = calcLatest(t);
      state.done = Math.abs(delta) <= restDelta;
      state.value = state.done ? target2 : latest;
    };
    let timeReachedBoundary;
    let spring$1;
    const checkCatchBoundary = (t) => {
      if (!isOutOfBounds(state.value))
        return;
      timeReachedBoundary = t;
      spring$1 = spring({
        keyframes: [state.value, nearestBoundary(state.value)],
        velocity: getGeneratorVelocity(calcLatest, t, state.value),
        // TODO: This should be passing * 1000
        damping: bounceDamping,
        stiffness: bounceStiffness,
        restDelta,
        restSpeed
      });
    };
    checkCatchBoundary(0);
    return {
      calculatedDuration: null,
      next: (t) => {
        let hasUpdatedFrame = false;
        if (!spring$1 && timeReachedBoundary === void 0) {
          hasUpdatedFrame = true;
          applyFriction(t);
          checkCatchBoundary(t);
        }
        if (timeReachedBoundary !== void 0 && t >= timeReachedBoundary) {
          return spring$1.next(t - timeReachedBoundary);
        } else {
          !hasUpdatedFrame && applyFriction(t);
          return state;
        }
      }
    };
  }
  function createMixers(output, ease2, customMixer) {
    const mixers = [];
    const mixerFactory = customMixer || MotionGlobalConfig.mix || mix;
    const numMixers = output.length - 1;
    for (let i = 0; i < numMixers; i++) {
      let mixer = mixerFactory(output[i], output[i + 1]);
      if (ease2) {
        const easingFunction = Array.isArray(ease2) ? ease2[i] || noop : ease2;
        mixer = pipe(easingFunction, mixer);
      }
      mixers.push(mixer);
    }
    return mixers;
  }
  function interpolate(input2, output, { clamp: isClamp = true, ease: ease2, mixer } = {}) {
    const inputLength = input2.length;
    invariant(inputLength === output.length, "Both input and output ranges must be the same length", "range-length");
    if (inputLength === 1)
      return () => output[0];
    if (inputLength === 2 && output[0] === output[1])
      return () => output[1];
    const isZeroDeltaRange = input2[0] === input2[1];
    if (input2[0] > input2[inputLength - 1]) {
      input2 = [...input2].reverse();
      output = [...output].reverse();
    }
    const mixers = createMixers(output, ease2, mixer);
    const numMixers = mixers.length;
    const interpolator = (v) => {
      if (isZeroDeltaRange && v < input2[0])
        return output[0];
      let i = 0;
      if (numMixers > 1) {
        for (; i < input2.length - 2; i++) {
          if (v < input2[i + 1])
            break;
        }
      }
      const progressInRange = /* @__PURE__ */ progress$1(input2[i], input2[i + 1], v);
      return mixers[i](progressInRange);
    };
    return isClamp ? (v) => interpolator(clamp(input2[0], input2[inputLength - 1], v)) : interpolator;
  }
  function fillOffset(offset, remaining) {
    const min = offset[offset.length - 1];
    for (let i = 1; i <= remaining; i++) {
      const offsetProgress = /* @__PURE__ */ progress$1(0, remaining, i);
      offset.push(mixNumber$1(min, 1, offsetProgress));
    }
  }
  function defaultOffset(arr) {
    const offset = [0];
    fillOffset(offset, arr.length - 1);
    return offset;
  }
  function convertOffsetToTimes(offset, duration) {
    return offset.map((o) => o * duration);
  }
  function defaultEasing(values, easing) {
    return values.map(() => easing || easeInOut).splice(0, values.length - 1);
  }
  function keyframes({ duration = 300, keyframes: keyframeValues, times, ease: ease2 = "easeInOut" }) {
    const easingFunctions = isEasingArray(ease2) ? ease2.map(easingDefinitionToFunction) : easingDefinitionToFunction(ease2);
    const state = {
      done: false,
      value: keyframeValues[0]
    };
    const absoluteTimes = convertOffsetToTimes(
      // Only use the provided offsets if they're the correct length
      // TODO Maybe we should warn here if there's a length mismatch
      times && times.length === keyframeValues.length ? times : defaultOffset(keyframeValues),
      duration
    );
    const mapTimeToKeyframe = interpolate(absoluteTimes, keyframeValues, {
      ease: Array.isArray(easingFunctions) ? easingFunctions : defaultEasing(keyframeValues, easingFunctions)
    });
    return {
      calculatedDuration: duration,
      next: (t) => {
        state.value = mapTimeToKeyframe(t);
        state.done = t >= duration;
        return state;
      }
    };
  }
  const isNotNull = (value) => value !== null;
  function getFinalKeyframe(keyframes2, { repeat, repeatType = "loop" }, finalKeyframe, speed = 1) {
    const resolvedKeyframes = keyframes2.filter(isNotNull);
    const useFirstKeyframe = speed < 0 || repeat && repeatType !== "loop" && repeat % 2 === 1;
    const index = useFirstKeyframe ? 0 : resolvedKeyframes.length - 1;
    return !index || finalKeyframe === void 0 ? resolvedKeyframes[index] : finalKeyframe;
  }
  const transitionTypeMap = {
    decay: inertia,
    inertia,
    tween: keyframes,
    keyframes,
    spring
  };
  function replaceTransitionType(transition) {
    if (typeof transition.type === "string") {
      transition.type = transitionTypeMap[transition.type];
    }
  }
  class WithPromise {
    constructor() {
      this.updateFinished();
    }
    get finished() {
      return this._finished;
    }
    updateFinished() {
      this._finished = new Promise((resolve) => {
        this.resolve = resolve;
      });
    }
    notifyFinished() {
      this.resolve();
    }
    /**
     * Allows the animation to be awaited.
     *
     * @deprecated Use `finished` instead.
     */
    then(onResolve, onReject) {
      return this.finished.then(onResolve, onReject);
    }
  }
  const percentToProgress = (percent2) => percent2 / 100;
  class JSAnimation extends WithPromise {
    constructor(options) {
      super();
      this.state = "idle";
      this.startTime = null;
      this.isStopped = false;
      this.currentTime = 0;
      this.holdTime = null;
      this.playbackSpeed = 1;
      this.delayState = {
        done: false,
        value: void 0
      };
      this.stop = () => {
        var _a2, _b;
        const { motionValue: motionValue2 } = this.options;
        if (motionValue2 && motionValue2.updatedAt !== time.now()) {
          this.tick(time.now());
        }
        this.isStopped = true;
        if (this.state === "idle")
          return;
        this.teardown();
        (_b = (_a2 = this.options).onStop) == null ? void 0 : _b.call(_a2);
      };
      this.options = options;
      this.initAnimation();
      this.play();
      if (options.autoplay === false)
        this.pause();
    }
    initAnimation() {
      const { options } = this;
      replaceTransitionType(options);
      const { type = keyframes, repeat = 0, repeatDelay = 0, repeatType, velocity = 0 } = options;
      let { keyframes: keyframes$1 } = options;
      const generatorFactory = type || keyframes;
      if (generatorFactory !== keyframes && typeof keyframes$1[0] !== "number") {
        this.mixKeyframes = pipe(percentToProgress, mix(keyframes$1[0], keyframes$1[1]));
        keyframes$1 = [0, 100];
      }
      const generator = generatorFactory({ ...options, keyframes: keyframes$1 });
      if (repeatType === "mirror") {
        this.mirroredGenerator = generatorFactory({
          ...options,
          keyframes: [...keyframes$1].reverse(),
          velocity: -velocity
        });
      }
      if (generator.calculatedDuration === null) {
        generator.calculatedDuration = calcGeneratorDuration(generator);
      }
      const { calculatedDuration } = generator;
      this.calculatedDuration = calculatedDuration;
      this.resolvedDuration = calculatedDuration + repeatDelay;
      this.totalDuration = this.resolvedDuration * (repeat + 1) - repeatDelay;
      this.generator = generator;
    }
    updateTime(timestamp) {
      const animationTime = Math.round(timestamp - this.startTime) * this.playbackSpeed;
      if (this.holdTime !== null) {
        this.currentTime = this.holdTime;
      } else {
        this.currentTime = animationTime;
      }
    }
    tick(timestamp, sample = false) {
      const { generator, totalDuration, mixKeyframes, mirroredGenerator, resolvedDuration, calculatedDuration } = this;
      if (this.startTime === null)
        return generator.next(0);
      const { delay: delay2 = 0, keyframes: keyframes2, repeat, repeatType, repeatDelay, type, onUpdate, finalKeyframe } = this.options;
      if (this.speed > 0) {
        this.startTime = Math.min(this.startTime, timestamp);
      } else if (this.speed < 0) {
        this.startTime = Math.min(timestamp - totalDuration / this.speed, this.startTime);
      }
      if (sample) {
        this.currentTime = timestamp;
      } else {
        this.updateTime(timestamp);
      }
      const timeWithoutDelay = this.currentTime - delay2 * (this.playbackSpeed >= 0 ? 1 : -1);
      const isInDelayPhase = this.playbackSpeed >= 0 ? timeWithoutDelay < 0 : timeWithoutDelay > totalDuration;
      this.currentTime = Math.max(timeWithoutDelay, 0);
      if (this.state === "finished" && this.holdTime === null) {
        this.currentTime = totalDuration;
      }
      let elapsed = this.currentTime;
      let frameGenerator = generator;
      if (repeat) {
        const progress2 = Math.min(this.currentTime, totalDuration) / resolvedDuration;
        let currentIteration = Math.floor(progress2);
        let iterationProgress = progress2 % 1;
        if (!iterationProgress && progress2 >= 1) {
          iterationProgress = 1;
        }
        iterationProgress === 1 && currentIteration--;
        currentIteration = Math.min(currentIteration, repeat + 1);
        const isOddIteration = Boolean(currentIteration % 2);
        if (isOddIteration) {
          if (repeatType === "reverse") {
            iterationProgress = 1 - iterationProgress;
            if (repeatDelay) {
              iterationProgress -= repeatDelay / resolvedDuration;
            }
          } else if (repeatType === "mirror") {
            frameGenerator = mirroredGenerator;
          }
        }
        elapsed = clamp(0, 1, iterationProgress) * resolvedDuration;
      }
      let state;
      if (isInDelayPhase) {
        this.delayState.value = keyframes2[0];
        state = this.delayState;
      } else {
        state = frameGenerator.next(elapsed);
      }
      if (mixKeyframes && !isInDelayPhase) {
        state.value = mixKeyframes(state.value);
      }
      let { done } = state;
      if (!isInDelayPhase && calculatedDuration !== null) {
        done = this.playbackSpeed >= 0 ? this.currentTime >= totalDuration : this.currentTime <= 0;
      }
      const isAnimationFinished = this.holdTime === null && (this.state === "finished" || this.state === "running" && done);
      if (isAnimationFinished && type !== inertia) {
        state.value = getFinalKeyframe(keyframes2, this.options, finalKeyframe, this.speed);
      }
      if (onUpdate) {
        onUpdate(state.value);
      }
      if (isAnimationFinished) {
        this.finish();
      }
      return state;
    }
    /**
     * Allows the returned animation to be awaited or promise-chained. Currently
     * resolves when the animation finishes at all but in a future update could/should
     * reject if its cancels.
     */
    then(resolve, reject) {
      return this.finished.then(resolve, reject);
    }
    get duration() {
      return /* @__PURE__ */ millisecondsToSeconds(this.calculatedDuration);
    }
    get iterationDuration() {
      const { delay: delay2 = 0 } = this.options || {};
      return this.duration + /* @__PURE__ */ millisecondsToSeconds(delay2);
    }
    get time() {
      return /* @__PURE__ */ millisecondsToSeconds(this.currentTime);
    }
    set time(newTime) {
      newTime = /* @__PURE__ */ secondsToMilliseconds(newTime);
      this.currentTime = newTime;
      if (this.startTime === null || this.holdTime !== null || this.playbackSpeed === 0) {
        this.holdTime = newTime;
      } else if (this.driver) {
        this.startTime = this.driver.now() - newTime / this.playbackSpeed;
      }
      if (this.driver) {
        this.driver.start(false);
      } else {
        this.startTime = 0;
        this.state = "paused";
        this.holdTime = newTime;
        this.tick(newTime);
      }
    }
    /**
     * Returns the generator's velocity at the current time in units/second.
     * Uses the analytical derivative when available (springs), avoiding
     * the MotionValue's frame-dependent velocity estimation.
     */
    getGeneratorVelocity() {
      const t = this.currentTime;
      if (t <= 0)
        return this.options.velocity || 0;
      if (this.generator.velocity) {
        return this.generator.velocity(t);
      }
      const current = this.generator.next(t).value;
      return getGeneratorVelocity((s) => this.generator.next(s).value, t, current);
    }
    get speed() {
      return this.playbackSpeed;
    }
    set speed(newSpeed) {
      const hasChanged = this.playbackSpeed !== newSpeed;
      if (hasChanged && this.driver) {
        this.updateTime(time.now());
      }
      this.playbackSpeed = newSpeed;
      if (hasChanged && this.driver) {
        this.time = /* @__PURE__ */ millisecondsToSeconds(this.currentTime);
      }
    }
    play() {
      var _a2, _b;
      if (this.isStopped)
        return;
      const { driver = frameloopDriver, startTime } = this.options;
      if (!this.driver) {
        this.driver = driver((timestamp) => this.tick(timestamp));
      }
      (_b = (_a2 = this.options).onPlay) == null ? void 0 : _b.call(_a2);
      const now2 = this.driver.now();
      if (this.state === "finished") {
        this.updateFinished();
        this.startTime = now2;
      } else if (this.holdTime !== null) {
        this.startTime = now2 - this.holdTime;
      } else if (!this.startTime) {
        this.startTime = startTime ?? now2;
      }
      if (this.state === "finished" && this.speed < 0) {
        this.startTime += this.calculatedDuration;
      }
      this.holdTime = null;
      this.state = "running";
      this.driver.start();
    }
    pause() {
      this.state = "paused";
      this.updateTime(time.now());
      this.holdTime = this.currentTime;
    }
    complete() {
      if (this.state !== "running") {
        this.play();
      }
      this.state = "finished";
      this.holdTime = null;
    }
    finish() {
      var _a2, _b;
      this.notifyFinished();
      this.teardown();
      this.state = "finished";
      (_b = (_a2 = this.options).onComplete) == null ? void 0 : _b.call(_a2);
    }
    cancel() {
      var _a2, _b;
      this.holdTime = null;
      this.startTime = 0;
      this.tick(0);
      this.teardown();
      (_b = (_a2 = this.options).onCancel) == null ? void 0 : _b.call(_a2);
    }
    teardown() {
      this.state = "idle";
      this.stopDriver();
      this.startTime = this.holdTime = null;
    }
    stopDriver() {
      if (!this.driver)
        return;
      this.driver.stop();
      this.driver = void 0;
    }
    sample(sampleTime) {
      this.startTime = 0;
      return this.tick(sampleTime, true);
    }
    attachTimeline(timeline) {
      var _a2;
      if (this.options.allowFlatten) {
        this.options.type = "keyframes";
        this.options.ease = "linear";
        this.initAnimation();
      }
      (_a2 = this.driver) == null ? void 0 : _a2.stop();
      return timeline.observe(this);
    }
  }
  function fillWildcards(keyframes2) {
    for (let i = 1; i < keyframes2.length; i++) {
      keyframes2[i] ?? (keyframes2[i] = keyframes2[i - 1]);
    }
  }
  const radToDeg = (rad) => rad * 180 / Math.PI;
  const rotate = (v) => {
    const angle = radToDeg(Math.atan2(v[1], v[0]));
    return rebaseAngle(angle);
  };
  const matrix2dParsers = {
    x: 4,
    y: 5,
    translateX: 4,
    translateY: 5,
    scaleX: 0,
    scaleY: 3,
    scale: (v) => (Math.abs(v[0]) + Math.abs(v[3])) / 2,
    rotate,
    rotateZ: rotate,
    skewX: (v) => radToDeg(Math.atan(v[1])),
    skewY: (v) => radToDeg(Math.atan(v[2])),
    skew: (v) => (Math.abs(v[1]) + Math.abs(v[2])) / 2
  };
  const rebaseAngle = (angle) => {
    angle = angle % 360;
    if (angle < 0)
      angle += 360;
    return angle;
  };
  const rotateZ = rotate;
  const scaleX = (v) => Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  const scaleY = (v) => Math.sqrt(v[4] * v[4] + v[5] * v[5]);
  const matrix3dParsers = {
    x: 12,
    y: 13,
    z: 14,
    translateX: 12,
    translateY: 13,
    translateZ: 14,
    scaleX,
    scaleY,
    scale: (v) => (scaleX(v) + scaleY(v)) / 2,
    rotateX: (v) => rebaseAngle(radToDeg(Math.atan2(v[6], v[5]))),
    rotateY: (v) => rebaseAngle(radToDeg(Math.atan2(-v[2], v[0]))),
    rotateZ,
    rotate: rotateZ,
    skewX: (v) => radToDeg(Math.atan(v[4])),
    skewY: (v) => radToDeg(Math.atan(v[1])),
    skew: (v) => (Math.abs(v[1]) + Math.abs(v[4])) / 2
  };
  function defaultTransformValue(name2) {
    return name2.includes("scale") ? 1 : 0;
  }
  function parseValueFromTransform(transform2, name2) {
    if (!transform2 || transform2 === "none") {
      return defaultTransformValue(name2);
    }
    const matrix3dMatch = transform2.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);
    let parsers;
    let match;
    if (matrix3dMatch) {
      parsers = matrix3dParsers;
      match = matrix3dMatch;
    } else {
      const matrix2dMatch = transform2.match(/^matrix\(([-\d.e\s,]+)\)$/u);
      parsers = matrix2dParsers;
      match = matrix2dMatch;
    }
    if (!match) {
      return defaultTransformValue(name2);
    }
    const valueParser = parsers[name2];
    const values = match[1].split(",").map(convertTransformToNumber);
    return typeof valueParser === "function" ? valueParser(values) : values[valueParser];
  }
  const readTransformValue = (instance, name2) => {
    const { transform: transform2 = "none" } = getComputedStyle(instance);
    return parseValueFromTransform(transform2, name2);
  };
  function convertTransformToNumber(value) {
    return parseFloat(value.trim());
  }
  const transformPropOrder = [
    "transformPerspective",
    "x",
    "y",
    "z",
    "translateX",
    "translateY",
    "translateZ",
    "scale",
    "scaleX",
    "scaleY",
    "rotate",
    "rotateX",
    "rotateY",
    "rotateZ",
    "skew",
    "skewX",
    "skewY"
  ];
  const transformProps = /* @__PURE__ */ (() => new Set(transformPropOrder))();
  const isNumOrPxType = (v) => v === number || v === px;
  const transformKeys = /* @__PURE__ */ new Set(["x", "y", "z"]);
  const nonTranslationalTransformKeys = transformPropOrder.filter((key) => !transformKeys.has(key));
  function removeNonTranslationalTransform(visualElement) {
    const removedTransforms = [];
    nonTranslationalTransformKeys.forEach((key) => {
      const value = visualElement.getValue(key);
      if (value !== void 0) {
        removedTransforms.push([key, value.get()]);
        value.set(key.startsWith("scale") ? 1 : 0);
      }
    });
    return removedTransforms;
  }
  const positionalValues = {
    // Dimensions
    width: ({ x }, { paddingLeft = "0", paddingRight = "0", boxSizing }) => {
      const width = x.max - x.min;
      return boxSizing === "border-box" ? width : width - parseFloat(paddingLeft) - parseFloat(paddingRight);
    },
    height: ({ y }, { paddingTop = "0", paddingBottom = "0", boxSizing }) => {
      const height = y.max - y.min;
      return boxSizing === "border-box" ? height : height - parseFloat(paddingTop) - parseFloat(paddingBottom);
    },
    top: (_bbox, { top }) => parseFloat(top),
    left: (_bbox, { left }) => parseFloat(left),
    bottom: ({ y }, { top }) => parseFloat(top) + (y.max - y.min),
    right: ({ x }, { left }) => parseFloat(left) + (x.max - x.min),
    // Transform
    x: (_bbox, { transform: transform2 }) => parseValueFromTransform(transform2, "x"),
    y: (_bbox, { transform: transform2 }) => parseValueFromTransform(transform2, "y")
  };
  positionalValues.translateX = positionalValues.x;
  positionalValues.translateY = positionalValues.y;
  const toResolve = /* @__PURE__ */ new Set();
  let isScheduled = false;
  let anyNeedsMeasurement = false;
  let isForced = false;
  function measureAllKeyframes() {
    if (anyNeedsMeasurement) {
      const resolversToMeasure = Array.from(toResolve).filter((resolver) => resolver.needsMeasurement);
      const elementsToMeasure = new Set(resolversToMeasure.map((resolver) => resolver.element));
      const transformsToRestore = /* @__PURE__ */ new Map();
      elementsToMeasure.forEach((element) => {
        const removedTransforms = removeNonTranslationalTransform(element);
        if (!removedTransforms.length)
          return;
        transformsToRestore.set(element, removedTransforms);
        element.render();
      });
      resolversToMeasure.forEach((resolver) => resolver.measureInitialState());
      elementsToMeasure.forEach((element) => {
        element.render();
        const restore = transformsToRestore.get(element);
        if (restore) {
          restore.forEach(([key, value]) => {
            var _a2;
            (_a2 = element.getValue(key)) == null ? void 0 : _a2.set(value);
          });
        }
      });
      resolversToMeasure.forEach((resolver) => resolver.measureEndState());
      resolversToMeasure.forEach((resolver) => {
        if (resolver.suspendedScrollY !== void 0) {
          window.scrollTo(0, resolver.suspendedScrollY);
        }
      });
    }
    anyNeedsMeasurement = false;
    isScheduled = false;
    toResolve.forEach((resolver) => resolver.complete(isForced));
    toResolve.clear();
  }
  function readAllKeyframes() {
    toResolve.forEach((resolver) => {
      resolver.readKeyframes();
      if (resolver.needsMeasurement) {
        anyNeedsMeasurement = true;
      }
    });
  }
  function flushKeyframeResolvers() {
    isForced = true;
    readAllKeyframes();
    measureAllKeyframes();
    isForced = false;
  }
  class KeyframeResolver {
    constructor(unresolvedKeyframes, onComplete, name2, motionValue2, element, isAsync = false) {
      this.state = "pending";
      this.isAsync = false;
      this.needsMeasurement = false;
      this.unresolvedKeyframes = [...unresolvedKeyframes];
      this.onComplete = onComplete;
      this.name = name2;
      this.motionValue = motionValue2;
      this.element = element;
      this.isAsync = isAsync;
    }
    scheduleResolve() {
      this.state = "scheduled";
      if (this.isAsync) {
        toResolve.add(this);
        if (!isScheduled) {
          isScheduled = true;
          frame.read(readAllKeyframes);
          frame.resolveKeyframes(measureAllKeyframes);
        }
      } else {
        this.readKeyframes();
        this.complete();
      }
    }
    readKeyframes() {
      const { unresolvedKeyframes, name: name2, element, motionValue: motionValue2 } = this;
      if (unresolvedKeyframes[0] === null) {
        const currentValue = motionValue2 == null ? void 0 : motionValue2.get();
        const finalKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1];
        if (currentValue !== void 0) {
          unresolvedKeyframes[0] = currentValue;
        } else if (element && name2) {
          const valueAsRead = element.readValue(name2, finalKeyframe);
          if (valueAsRead !== void 0 && valueAsRead !== null) {
            unresolvedKeyframes[0] = valueAsRead;
          }
        }
        if (unresolvedKeyframes[0] === void 0) {
          unresolvedKeyframes[0] = finalKeyframe;
        }
        if (motionValue2 && currentValue === void 0) {
          motionValue2.set(unresolvedKeyframes[0]);
        }
      }
      fillWildcards(unresolvedKeyframes);
    }
    setFinalKeyframe() {
    }
    measureInitialState() {
    }
    renderEndStyles() {
    }
    measureEndState() {
    }
    complete(isForcedComplete = false) {
      this.state = "complete";
      this.onComplete(this.unresolvedKeyframes, this.finalKeyframe, isForcedComplete);
      toResolve.delete(this);
    }
    cancel() {
      if (this.state === "scheduled") {
        toResolve.delete(this);
        this.state = "pending";
      }
    }
    resume() {
      if (this.state === "pending")
        this.scheduleResolve();
    }
  }
  const isCSSVar = (name2) => name2.startsWith("--");
  function setStyle(element, name2, value) {
    isCSSVar(name2) ? element.style.setProperty(name2, value) : element.style[name2] = value;
  }
  const supportsFlags = {};
  function memoSupports(callback, supportsFlag) {
    const memoized = /* @__PURE__ */ memo(callback);
    return () => supportsFlags[supportsFlag] ?? memoized();
  }
  const supportsScrollTimeline = /* @__PURE__ */ memoSupports(() => window.ScrollTimeline !== void 0, "scrollTimeline");
  const supportsLinearEasing = /* @__PURE__ */ memoSupports(() => {
    try {
      document.createElement("div").animate({ opacity: 0 }, { easing: "linear(0, 1)" });
    } catch (e) {
      return false;
    }
    return true;
  }, "linearEasing");
  const cubicBezierAsString = ([a, b, c, d]) => `cubic-bezier(${a}, ${b}, ${c}, ${d})`;
  const supportedWaapiEasing = {
    linear: "linear",
    ease: "ease",
    easeIn: "ease-in",
    easeOut: "ease-out",
    easeInOut: "ease-in-out",
    circIn: /* @__PURE__ */ cubicBezierAsString([0, 0.65, 0.55, 1]),
    circOut: /* @__PURE__ */ cubicBezierAsString([0.55, 0, 1, 0.45]),
    backIn: /* @__PURE__ */ cubicBezierAsString([0.31, 0.01, 0.66, -0.59]),
    backOut: /* @__PURE__ */ cubicBezierAsString([0.33, 1.53, 0.69, 0.99])
  };
  function mapEasingToNativeEasing(easing, duration) {
    if (!easing) {
      return void 0;
    } else if (typeof easing === "function") {
      return supportsLinearEasing() ? generateLinearEasing(easing, duration) : "ease-out";
    } else if (isBezierDefinition(easing)) {
      return cubicBezierAsString(easing);
    } else if (Array.isArray(easing)) {
      return easing.map((segmentEasing) => mapEasingToNativeEasing(segmentEasing, duration) || supportedWaapiEasing.easeOut);
    } else {
      return supportedWaapiEasing[easing];
    }
  }
  function startWaapiAnimation(element, valueName, keyframes2, { delay: delay2 = 0, duration = 300, repeat = 0, repeatType = "loop", ease: ease2 = "easeOut", times } = {}, pseudoElement = void 0) {
    const keyframeOptions = {
      [valueName]: keyframes2
    };
    if (times)
      keyframeOptions.offset = times;
    const easing = mapEasingToNativeEasing(ease2, duration);
    if (Array.isArray(easing))
      keyframeOptions.easing = easing;
    const options = {
      delay: delay2,
      duration,
      easing: !Array.isArray(easing) ? easing : "linear",
      fill: "both",
      iterations: repeat + 1,
      direction: repeatType === "reverse" ? "alternate" : "normal"
    };
    if (pseudoElement)
      options.pseudoElement = pseudoElement;
    const animation = element.animate(keyframeOptions, options);
    return animation;
  }
  function isGenerator(type) {
    return typeof type === "function" && "applyToOptions" in type;
  }
  function applyGeneratorOptions({ type, ...options }) {
    if (isGenerator(type) && supportsLinearEasing()) {
      return type.applyToOptions(options);
    } else {
      options.duration ?? (options.duration = 300);
      options.ease ?? (options.ease = "easeOut");
    }
    return options;
  }
  class NativeAnimation extends WithPromise {
    constructor(options) {
      super();
      this.finishedTime = null;
      this.isStopped = false;
      this.manualStartTime = null;
      if (!options)
        return;
      const { element, name: name2, keyframes: keyframes2, pseudoElement, allowFlatten = false, finalKeyframe, onComplete } = options;
      this.isPseudoElement = Boolean(pseudoElement);
      this.allowFlatten = allowFlatten;
      this.options = options;
      invariant(typeof options.type !== "string", `Mini animate() doesn't support "type" as a string.`, "mini-spring");
      const transition = applyGeneratorOptions(options);
      this.animation = startWaapiAnimation(element, name2, keyframes2, transition, pseudoElement);
      if (transition.autoplay === false) {
        this.animation.pause();
      }
      this.animation.onfinish = () => {
        this.finishedTime = this.time;
        if (!pseudoElement) {
          const keyframe = getFinalKeyframe(keyframes2, this.options, finalKeyframe, this.speed);
          if (this.updateMotionValue) {
            this.updateMotionValue(keyframe);
          }
          setStyle(element, name2, keyframe);
          this.animation.cancel();
        }
        onComplete == null ? void 0 : onComplete();
        this.notifyFinished();
      };
    }
    play() {
      if (this.isStopped)
        return;
      this.manualStartTime = null;
      this.animation.play();
      if (this.state === "finished") {
        this.updateFinished();
      }
    }
    pause() {
      this.animation.pause();
    }
    complete() {
      var _a2, _b;
      (_b = (_a2 = this.animation).finish) == null ? void 0 : _b.call(_a2);
    }
    cancel() {
      try {
        this.animation.cancel();
      } catch (e) {
      }
    }
    stop() {
      if (this.isStopped)
        return;
      this.isStopped = true;
      const { state } = this;
      if (state === "idle" || state === "finished") {
        return;
      }
      if (this.updateMotionValue) {
        this.updateMotionValue();
      } else {
        this.commitStyles();
      }
      if (!this.isPseudoElement)
        this.cancel();
    }
    /**
     * WAAPI doesn't natively have any interruption capabilities.
     *
     * In this method, we commit styles back to the DOM before cancelling
     * the animation.
     *
     * This is designed to be overridden by NativeAnimationExtended, which
     * will create a renderless JS animation and sample it twice to calculate
     * its current value, "previous" value, and therefore allow
     * Motion to also correctly calculate velocity for any subsequent animation
     * while deferring the commit until the next animation frame.
     */
    commitStyles() {
      var _a2, _b, _c;
      const element = (_a2 = this.options) == null ? void 0 : _a2.element;
      if (!this.isPseudoElement && (element == null ? void 0 : element.isConnected)) {
        (_c = (_b = this.animation).commitStyles) == null ? void 0 : _c.call(_b);
      }
    }
    get duration() {
      var _a2, _b;
      const duration = ((_b = (_a2 = this.animation.effect) == null ? void 0 : _a2.getComputedTiming) == null ? void 0 : _b.call(_a2).duration) || 0;
      return /* @__PURE__ */ millisecondsToSeconds(Number(duration));
    }
    get iterationDuration() {
      const { delay: delay2 = 0 } = this.options || {};
      return this.duration + /* @__PURE__ */ millisecondsToSeconds(delay2);
    }
    get time() {
      return /* @__PURE__ */ millisecondsToSeconds(Number(this.animation.currentTime) || 0);
    }
    set time(newTime) {
      const wasFinished = this.finishedTime !== null;
      this.manualStartTime = null;
      this.finishedTime = null;
      this.animation.currentTime = /* @__PURE__ */ secondsToMilliseconds(newTime);
      if (wasFinished) {
        this.animation.pause();
      }
    }
    /**
     * The playback speed of the animation.
     * 1 = normal speed, 2 = double speed, 0.5 = half speed.
     */
    get speed() {
      return this.animation.playbackRate;
    }
    set speed(newSpeed) {
      if (newSpeed < 0)
        this.finishedTime = null;
      this.animation.playbackRate = newSpeed;
    }
    get state() {
      return this.finishedTime !== null ? "finished" : this.animation.playState;
    }
    get startTime() {
      return this.manualStartTime ?? Number(this.animation.startTime);
    }
    set startTime(newStartTime) {
      this.manualStartTime = this.animation.startTime = newStartTime;
    }
    /**
     * Attaches a timeline to the animation, for instance the `ScrollTimeline`.
     */
    attachTimeline({ timeline, rangeStart, rangeEnd, observe }) {
      var _a2;
      if (this.allowFlatten) {
        (_a2 = this.animation.effect) == null ? void 0 : _a2.updateTiming({ easing: "linear" });
      }
      this.animation.onfinish = null;
      if (timeline && supportsScrollTimeline()) {
        this.animation.timeline = timeline;
        if (rangeStart)
          this.animation.rangeStart = rangeStart;
        if (rangeEnd)
          this.animation.rangeEnd = rangeEnd;
        return noop;
      } else {
        return observe(this);
      }
    }
  }
  const unsupportedEasingFunctions = {
    anticipate,
    backInOut,
    circInOut
  };
  function isUnsupportedEase(key) {
    return key in unsupportedEasingFunctions;
  }
  function replaceStringEasing(transition) {
    if (typeof transition.ease === "string" && isUnsupportedEase(transition.ease)) {
      transition.ease = unsupportedEasingFunctions[transition.ease];
    }
  }
  const sampleDelta = 10;
  class NativeAnimationExtended extends NativeAnimation {
    constructor(options) {
      replaceStringEasing(options);
      replaceTransitionType(options);
      super(options);
      if (options.startTime !== void 0 && options.autoplay !== false) {
        this.startTime = options.startTime;
      }
      this.options = options;
    }
    /**
     * WAAPI doesn't natively have any interruption capabilities.
     *
     * Rather than read committed styles back out of the DOM, we can
     * create a renderless JS animation and sample it twice to calculate
     * its current value, "previous" value, and therefore allow
     * Motion to calculate velocity for any subsequent animation.
     */
    updateMotionValue(value) {
      const { motionValue: motionValue2, onUpdate, onComplete, element, ...options } = this.options;
      if (!motionValue2)
        return;
      if (value !== void 0) {
        motionValue2.set(value);
        return;
      }
      const sampleAnimation = new JSAnimation({
        ...options,
        autoplay: false
      });
      const sampleTime = Math.max(sampleDelta, time.now() - this.startTime);
      const delta = clamp(0, sampleDelta, sampleTime - sampleDelta);
      const current = sampleAnimation.sample(sampleTime).value;
      const { name: name2 } = this.options;
      if (element && name2)
        setStyle(element, name2, current);
      motionValue2.setWithVelocity(sampleAnimation.sample(Math.max(0, sampleTime - delta)).value, current, delta);
      sampleAnimation.stop();
    }
  }
  const isAnimatable = (value, name2) => {
    if (name2 === "zIndex")
      return false;
    if (typeof value === "number" || Array.isArray(value))
      return true;
    if (typeof value === "string" && // It's animatable if we have a string
    (complex.test(value) || value === "0") && // And it contains numbers and/or colors
    !value.startsWith("url(")) {
      return true;
    }
    return false;
  };
  function hasKeyframesChanged(keyframes2) {
    const current = keyframes2[0];
    if (keyframes2.length === 1)
      return true;
    for (let i = 0; i < keyframes2.length; i++) {
      if (keyframes2[i] !== current)
        return true;
    }
  }
  function canAnimate(keyframes2, name2, type, velocity) {
    const originKeyframe = keyframes2[0];
    if (originKeyframe === null) {
      return false;
    }
    if (name2 === "display" || name2 === "visibility")
      return true;
    const targetKeyframe = keyframes2[keyframes2.length - 1];
    const isOriginAnimatable = isAnimatable(originKeyframe, name2);
    const isTargetAnimatable = isAnimatable(targetKeyframe, name2);
    warning(isOriginAnimatable === isTargetAnimatable, `You are trying to animate ${name2} from "${originKeyframe}" to "${targetKeyframe}". "${isOriginAnimatable ? targetKeyframe : originKeyframe}" is not an animatable value.`, "value-not-animatable");
    if (!isOriginAnimatable || !isTargetAnimatable) {
      return false;
    }
    return hasKeyframesChanged(keyframes2) || (type === "spring" || isGenerator(type)) && velocity;
  }
  function makeAnimationInstant(options) {
    options.duration = 0;
    options.type = "keyframes";
  }
  const acceleratedValues = /* @__PURE__ */ new Set([
    "opacity",
    "clipPath",
    "filter",
    "transform"
    // TODO: Can be accelerated but currently disabled until https://issues.chromium.org/issues/41491098 is resolved
    // or until we implement support for linear() easing.
    // "background-color"
  ]);
  const browserColorFunctions = /^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;
  function hasBrowserOnlyColors(keyframes2) {
    for (let i = 0; i < keyframes2.length; i++) {
      if (typeof keyframes2[i] === "string" && browserColorFunctions.test(keyframes2[i])) {
        return true;
      }
    }
    return false;
  }
  const colorProperties = /* @__PURE__ */ new Set([
    "color",
    "backgroundColor",
    "outlineColor",
    "fill",
    "stroke",
    "borderColor",
    "borderTopColor",
    "borderRightColor",
    "borderBottomColor",
    "borderLeftColor"
  ]);
  const supportsWaapi = /* @__PURE__ */ memo(() => Object.hasOwnProperty.call(Element.prototype, "animate"));
  function supportsBrowserAnimation(options) {
    var _a2;
    const { motionValue: motionValue2, name: name2, repeatDelay, repeatType, damping, type, keyframes: keyframes2 } = options;
    const subject = (_a2 = motionValue2 == null ? void 0 : motionValue2.owner) == null ? void 0 : _a2.current;
    if (!(subject instanceof HTMLElement)) {
      return false;
    }
    const { onUpdate, transformTemplate } = motionValue2.owner.getProps();
    return supportsWaapi() && name2 && /**
     * Force WAAPI for color properties with browser-only color formats
     * (oklch, oklab, lab, lch, etc.) that the JS animation path can't parse.
     */
    (acceleratedValues.has(name2) || colorProperties.has(name2) && hasBrowserOnlyColors(keyframes2)) && (name2 !== "transform" || !transformTemplate) && /**
     * If we're outputting values to onUpdate then we can't use WAAPI as there's
     * no way to read the value from WAAPI every frame.
     */
    !onUpdate && !repeatDelay && repeatType !== "mirror" && damping !== 0 && type !== "inertia";
  }
  const MAX_RESOLVE_DELAY = 40;
  class AsyncMotionValueAnimation extends WithPromise {
    constructor({ autoplay = true, delay: delay2 = 0, type = "keyframes", repeat = 0, repeatDelay = 0, repeatType = "loop", keyframes: keyframes2, name: name2, motionValue: motionValue2, element, ...options }) {
      var _a2;
      super();
      this.stop = () => {
        var _a3, _b;
        if (this._animation) {
          this._animation.stop();
          (_a3 = this.stopTimeline) == null ? void 0 : _a3.call(this);
        }
        (_b = this.keyframeResolver) == null ? void 0 : _b.cancel();
      };
      this.createdAt = time.now();
      const optionsWithDefaults = {
        autoplay,
        delay: delay2,
        type,
        repeat,
        repeatDelay,
        repeatType,
        name: name2,
        motionValue: motionValue2,
        element,
        ...options
      };
      const KeyframeResolver$1 = (element == null ? void 0 : element.KeyframeResolver) || KeyframeResolver;
      this.keyframeResolver = new KeyframeResolver$1(keyframes2, (resolvedKeyframes, finalKeyframe, forced) => this.onKeyframesResolved(resolvedKeyframes, finalKeyframe, optionsWithDefaults, !forced), name2, motionValue2, element);
      (_a2 = this.keyframeResolver) == null ? void 0 : _a2.scheduleResolve();
    }
    onKeyframesResolved(keyframes2, finalKeyframe, options, sync) {
      var _a2, _b;
      this.keyframeResolver = void 0;
      const { name: name2, type, velocity, delay: delay2, isHandoff, onUpdate } = options;
      this.resolvedAt = time.now();
      let canAnimateValue = true;
      if (!canAnimate(keyframes2, name2, type, velocity)) {
        canAnimateValue = false;
        if (MotionGlobalConfig.instantAnimations || !delay2) {
          onUpdate == null ? void 0 : onUpdate(getFinalKeyframe(keyframes2, options, finalKeyframe));
        }
        keyframes2[0] = keyframes2[keyframes2.length - 1];
        makeAnimationInstant(options);
        options.repeat = 0;
      }
      const startTime = sync ? !this.resolvedAt ? this.createdAt : this.resolvedAt - this.createdAt > MAX_RESOLVE_DELAY ? this.resolvedAt : this.createdAt : void 0;
      const resolvedOptions = {
        startTime,
        finalKeyframe,
        ...options,
        keyframes: keyframes2
      };
      const useWaapi = canAnimateValue && !isHandoff && supportsBrowserAnimation(resolvedOptions);
      const element = (_b = (_a2 = resolvedOptions.motionValue) == null ? void 0 : _a2.owner) == null ? void 0 : _b.current;
      let animation;
      if (useWaapi) {
        try {
          animation = new NativeAnimationExtended({
            ...resolvedOptions,
            element
          });
        } catch {
          animation = new JSAnimation(resolvedOptions);
        }
      } else {
        animation = new JSAnimation(resolvedOptions);
      }
      animation.finished.then(() => {
        this.notifyFinished();
      }).catch(noop);
      if (this.pendingTimeline) {
        this.stopTimeline = animation.attachTimeline(this.pendingTimeline);
        this.pendingTimeline = void 0;
      }
      this._animation = animation;
    }
    get finished() {
      if (!this._animation) {
        return this._finished;
      } else {
        return this.animation.finished;
      }
    }
    then(onResolve, _onReject) {
      return this.finished.finally(onResolve).then(() => {
      });
    }
    get animation() {
      var _a2;
      if (!this._animation) {
        (_a2 = this.keyframeResolver) == null ? void 0 : _a2.resume();
        flushKeyframeResolvers();
      }
      return this._animation;
    }
    get duration() {
      return this.animation.duration;
    }
    get iterationDuration() {
      return this.animation.iterationDuration;
    }
    get time() {
      return this.animation.time;
    }
    set time(newTime) {
      this.animation.time = newTime;
    }
    get speed() {
      return this.animation.speed;
    }
    get state() {
      return this.animation.state;
    }
    set speed(newSpeed) {
      this.animation.speed = newSpeed;
    }
    get startTime() {
      return this.animation.startTime;
    }
    attachTimeline(timeline) {
      if (this._animation) {
        this.stopTimeline = this.animation.attachTimeline(timeline);
      } else {
        this.pendingTimeline = timeline;
      }
      return () => this.stop();
    }
    play() {
      this.animation.play();
    }
    pause() {
      this.animation.pause();
    }
    complete() {
      this.animation.complete();
    }
    cancel() {
      var _a2;
      if (this._animation) {
        this.animation.cancel();
      }
      (_a2 = this.keyframeResolver) == null ? void 0 : _a2.cancel();
    }
  }
  function calcChildStagger(children, child, delayChildren, staggerChildren = 0, staggerDirection = 1) {
    const index = Array.from(children).sort((a, b) => a.sortNodePosition(b)).indexOf(child);
    const numChildren = children.size;
    const maxStaggerDuration = (numChildren - 1) * staggerChildren;
    const delayIsFunction = typeof delayChildren === "function";
    return delayIsFunction ? delayChildren(index, numChildren) : staggerDirection === 1 ? index * staggerChildren : maxStaggerDuration - index * staggerChildren;
  }
  const splitCSSVariableRegex = (
    // eslint-disable-next-line redos-detector/no-unsafe-regex -- false positive, as it can match a lot of words
    /^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u
  );
  function parseCSSVariable(current) {
    const match = splitCSSVariableRegex.exec(current);
    if (!match)
      return [,];
    const [, token1, token2, fallback] = match;
    return [`--${token1 ?? token2}`, fallback];
  }
  const maxDepth = 4;
  function getVariableValue(current, element, depth = 1) {
    invariant(depth <= maxDepth, `Max CSS variable fallback depth detected in property "${current}". This may indicate a circular fallback dependency.`, "max-css-var-depth");
    const [token, fallback] = parseCSSVariable(current);
    if (!token)
      return;
    const resolved = window.getComputedStyle(element).getPropertyValue(token);
    if (resolved) {
      const trimmed = resolved.trim();
      return isNumericalString(trimmed) ? parseFloat(trimmed) : trimmed;
    }
    return isCSSVariableToken(fallback) ? getVariableValue(fallback, element, depth + 1) : fallback;
  }
  const underDampedSpring = {
    type: "spring",
    stiffness: 500,
    damping: 25,
    restSpeed: 10
  };
  const criticallyDampedSpring = (target2) => ({
    type: "spring",
    stiffness: 550,
    damping: target2 === 0 ? 2 * Math.sqrt(550) : 30,
    restSpeed: 10
  });
  const keyframesTransition = {
    type: "keyframes",
    duration: 0.8
  };
  const ease = {
    type: "keyframes",
    ease: [0.25, 0.1, 0.35, 1],
    duration: 0.3
  };
  const getDefaultTransition = (valueKey, { keyframes: keyframes2 }) => {
    if (keyframes2.length > 2) {
      return keyframesTransition;
    } else if (transformProps.has(valueKey)) {
      return valueKey.startsWith("scale") ? criticallyDampedSpring(keyframes2[1]) : underDampedSpring;
    }
    return ease;
  };
  function resolveTransition(transition, parentTransition) {
    if ((transition == null ? void 0 : transition.inherit) && parentTransition) {
      const { inherit: _, ...rest } = transition;
      return { ...parentTransition, ...rest };
    }
    return transition;
  }
  function getValueTransition(transition, key) {
    const valueTransition = (transition == null ? void 0 : transition[key]) ?? (transition == null ? void 0 : transition["default"]) ?? transition;
    if (valueTransition !== transition) {
      return resolveTransition(valueTransition, transition);
    }
    return valueTransition;
  }
  const orchestrationKeys = /* @__PURE__ */ new Set([
    "when",
    "delay",
    "delayChildren",
    "staggerChildren",
    "staggerDirection",
    "repeat",
    "repeatType",
    "repeatDelay",
    "from",
    "elapsed"
  ]);
  function isTransitionDefined(transition) {
    for (const key in transition) {
      if (!orchestrationKeys.has(key))
        return true;
    }
    return false;
  }
  const animateMotionValue = (name2, value, target2, transition = {}, element, isHandoff) => (onComplete) => {
    const valueTransition = getValueTransition(transition, name2) || {};
    const delay2 = valueTransition.delay || transition.delay || 0;
    let { elapsed = 0 } = transition;
    elapsed = elapsed - /* @__PURE__ */ secondsToMilliseconds(delay2);
    const options = {
      keyframes: Array.isArray(target2) ? target2 : [null, target2],
      ease: "easeOut",
      velocity: value.getVelocity(),
      ...valueTransition,
      delay: -elapsed,
      onUpdate: (v) => {
        value.set(v);
        valueTransition.onUpdate && valueTransition.onUpdate(v);
      },
      onComplete: () => {
        onComplete();
        valueTransition.onComplete && valueTransition.onComplete();
      },
      name: name2,
      motionValue: value,
      element: isHandoff ? void 0 : element
    };
    if (!isTransitionDefined(valueTransition)) {
      Object.assign(options, getDefaultTransition(name2, options));
    }
    options.duration && (options.duration = /* @__PURE__ */ secondsToMilliseconds(options.duration));
    options.repeatDelay && (options.repeatDelay = /* @__PURE__ */ secondsToMilliseconds(options.repeatDelay));
    if (options.from !== void 0) {
      options.keyframes[0] = options.from;
    }
    let shouldSkip = false;
    if (options.type === false || options.duration === 0 && !options.repeatDelay) {
      makeAnimationInstant(options);
      if (options.delay === 0) {
        shouldSkip = true;
      }
    }
    if (MotionGlobalConfig.instantAnimations || MotionGlobalConfig.skipAnimations || (element == null ? void 0 : element.shouldSkipAnimations)) {
      shouldSkip = true;
      makeAnimationInstant(options);
      options.delay = 0;
    }
    options.allowFlatten = !valueTransition.type && !valueTransition.ease;
    if (shouldSkip && !isHandoff && value.get() !== void 0) {
      const finalKeyframe = getFinalKeyframe(options.keyframes, valueTransition);
      if (finalKeyframe !== void 0) {
        frame.update(() => {
          options.onUpdate(finalKeyframe);
          options.onComplete();
        });
        return;
      }
    }
    return valueTransition.isSync ? new JSAnimation(options) : new AsyncMotionValueAnimation(options);
  };
  function getValueState(visualElement) {
    const state = [{}, {}];
    visualElement == null ? void 0 : visualElement.values.forEach((value, key) => {
      state[0][key] = value.get();
      state[1][key] = value.getVelocity();
    });
    return state;
  }
  function resolveVariantFromProps(props, definition, custom, visualElement) {
    if (typeof definition === "function") {
      const [current, velocity] = getValueState(visualElement);
      definition = definition(custom !== void 0 ? custom : props.custom, current, velocity);
    }
    if (typeof definition === "string") {
      definition = props.variants && props.variants[definition];
    }
    if (typeof definition === "function") {
      const [current, velocity] = getValueState(visualElement);
      definition = definition(custom !== void 0 ? custom : props.custom, current, velocity);
    }
    return definition;
  }
  function resolveVariant(visualElement, definition, custom) {
    const props = visualElement.getProps();
    return resolveVariantFromProps(props, definition, custom !== void 0 ? custom : props.custom, visualElement);
  }
  const positionalKeys = /* @__PURE__ */ new Set([
    "width",
    "height",
    "top",
    "left",
    "right",
    "bottom",
    ...transformPropOrder
  ]);
  const MAX_VELOCITY_DELTA = 30;
  const isFloat = (value) => {
    return !isNaN(parseFloat(value));
  };
  const collectMotionValues = {
    current: void 0
  };
  class MotionValue {
    /**
     * @param init - The initiating value
     * @param config - Optional configuration options
     *
     * -  `transformer`: A function to transform incoming values with.
     */
    constructor(init, options = {}) {
      this.canTrackVelocity = null;
      this.events = {};
      this.updateAndNotify = (v) => {
        var _a2;
        const currentTime = time.now();
        if (this.updatedAt !== currentTime) {
          this.setPrevFrameValue();
        }
        this.prev = this.current;
        this.setCurrent(v);
        if (this.current !== this.prev) {
          (_a2 = this.events.change) == null ? void 0 : _a2.notify(this.current);
          if (this.dependents) {
            for (const dependent of this.dependents) {
              dependent.dirty();
            }
          }
        }
      };
      this.hasAnimated = false;
      this.setCurrent(init);
      this.owner = options.owner;
    }
    setCurrent(current) {
      this.current = current;
      this.updatedAt = time.now();
      if (this.canTrackVelocity === null && current !== void 0) {
        this.canTrackVelocity = isFloat(this.current);
      }
    }
    setPrevFrameValue(prevFrameValue = this.current) {
      this.prevFrameValue = prevFrameValue;
      this.prevUpdatedAt = this.updatedAt;
    }
    /**
     * Adds a function that will be notified when the `MotionValue` is updated.
     *
     * It returns a function that, when called, will cancel the subscription.
     *
     * When calling `onChange` inside a React component, it should be wrapped with the
     * `useEffect` hook. As it returns an unsubscribe function, this should be returned
     * from the `useEffect` function to ensure you don't add duplicate subscribers..
     *
     * ```jsx
     * export const MyComponent = () => {
     *   const x = useMotionValue(0)
     *   const y = useMotionValue(0)
     *   const opacity = useMotionValue(1)
     *
     *   useEffect(() => {
     *     function updateOpacity() {
     *       const maxXY = Math.max(x.get(), y.get())
     *       const newOpacity = transform(maxXY, [0, 100], [1, 0])
     *       opacity.set(newOpacity)
     *     }
     *
     *     const unsubscribeX = x.on("change", updateOpacity)
     *     const unsubscribeY = y.on("change", updateOpacity)
     *
     *     return () => {
     *       unsubscribeX()
     *       unsubscribeY()
     *     }
     *   }, [])
     *
     *   return <motion.div style={{ x }} />
     * }
     * ```
     *
     * @param subscriber - A function that receives the latest value.
     * @returns A function that, when called, will cancel this subscription.
     *
     * @deprecated
     */
    onChange(subscription) {
      return this.on("change", subscription);
    }
    on(eventName, callback) {
      if (!this.events[eventName]) {
        this.events[eventName] = new SubscriptionManager();
      }
      const unsubscribe = this.events[eventName].add(callback);
      if (eventName === "change") {
        return () => {
          unsubscribe();
          frame.read(() => {
            if (!this.events.change.getSize()) {
              this.stop();
            }
          });
        };
      }
      return unsubscribe;
    }
    clearListeners() {
      for (const eventManagers in this.events) {
        this.events[eventManagers].clear();
      }
    }
    /**
     * Attaches a passive effect to the `MotionValue`.
     */
    attach(passiveEffect, stopPassiveEffect) {
      this.passiveEffect = passiveEffect;
      this.stopPassiveEffect = stopPassiveEffect;
    }
    /**
     * Sets the state of the `MotionValue`.
     *
     * @remarks
     *
     * ```jsx
     * const x = useMotionValue(0)
     * x.set(10)
     * ```
     *
     * @param latest - Latest value to set.
     * @param render - Whether to notify render subscribers. Defaults to `true`
     *
     * @public
     */
    set(v) {
      if (!this.passiveEffect) {
        this.updateAndNotify(v);
      } else {
        this.passiveEffect(v, this.updateAndNotify);
      }
    }
    setWithVelocity(prev, current, delta) {
      this.set(current);
      this.prev = void 0;
      this.prevFrameValue = prev;
      this.prevUpdatedAt = this.updatedAt - delta;
    }
    /**
     * Set the state of the `MotionValue`, stopping any active animations,
     * effects, and resets velocity to `0`.
     */
    jump(v, endAnimation = true) {
      this.updateAndNotify(v);
      this.prev = v;
      this.prevUpdatedAt = this.prevFrameValue = void 0;
      endAnimation && this.stop();
      if (this.stopPassiveEffect)
        this.stopPassiveEffect();
    }
    dirty() {
      var _a2;
      (_a2 = this.events.change) == null ? void 0 : _a2.notify(this.current);
    }
    addDependent(dependent) {
      if (!this.dependents) {
        this.dependents = /* @__PURE__ */ new Set();
      }
      this.dependents.add(dependent);
    }
    removeDependent(dependent) {
      if (this.dependents) {
        this.dependents.delete(dependent);
      }
    }
    /**
     * Returns the latest state of `MotionValue`
     *
     * @returns - The latest state of `MotionValue`
     *
     * @public
     */
    get() {
      if (collectMotionValues.current) {
        collectMotionValues.current.push(this);
      }
      return this.current;
    }
    /**
     * @public
     */
    getPrevious() {
      return this.prev;
    }
    /**
     * Returns the latest velocity of `MotionValue`
     *
     * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical.
     *
     * @public
     */
    getVelocity() {
      const currentTime = time.now();
      if (!this.canTrackVelocity || this.prevFrameValue === void 0 || currentTime - this.updatedAt > MAX_VELOCITY_DELTA) {
        return 0;
      }
      const delta = Math.min(this.updatedAt - this.prevUpdatedAt, MAX_VELOCITY_DELTA);
      return velocityPerSecond(parseFloat(this.current) - parseFloat(this.prevFrameValue), delta);
    }
    /**
     * Registers a new animation to control this `MotionValue`. Only one
     * animation can drive a `MotionValue` at one time.
     *
     * ```jsx
     * value.start()
     * ```
     *
     * @param animation - A function that starts the provided animation
     */
    start(startAnimation) {
      this.stop();
      return new Promise((resolve) => {
        this.hasAnimated = true;
        this.animation = startAnimation(resolve);
        if (this.events.animationStart) {
          this.events.animationStart.notify();
        }
      }).then(() => {
        if (this.events.animationComplete) {
          this.events.animationComplete.notify();
        }
        this.clearAnimation();
      });
    }
    /**
     * Stop the currently active animation.
     *
     * @public
     */
    stop() {
      if (this.animation) {
        this.animation.stop();
        if (this.events.animationCancel) {
          this.events.animationCancel.notify();
        }
      }
      this.clearAnimation();
    }
    /**
     * Returns `true` if this value is currently animating.
     *
     * @public
     */
    isAnimating() {
      return !!this.animation;
    }
    clearAnimation() {
      delete this.animation;
    }
    /**
     * Destroy and clean up subscribers to this `MotionValue`.
     *
     * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically
     * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually
     * created a `MotionValue` via the `motionValue` function.
     *
     * @public
     */
    destroy() {
      var _a2, _b;
      (_a2 = this.dependents) == null ? void 0 : _a2.clear();
      (_b = this.events.destroy) == null ? void 0 : _b.notify();
      this.clearListeners();
      this.stop();
      if (this.stopPassiveEffect) {
        this.stopPassiveEffect();
      }
    }
  }
  function motionValue(init, options) {
    return new MotionValue(init, options);
  }
  const isKeyframesTarget = (v) => {
    return Array.isArray(v);
  };
  function setMotionValue(visualElement, key, value) {
    if (visualElement.hasValue(key)) {
      visualElement.getValue(key).set(value);
    } else {
      visualElement.addValue(key, motionValue(value));
    }
  }
  function resolveFinalValueInKeyframes(v) {
    return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v;
  }
  function setTarget(visualElement, definition) {
    const resolved = resolveVariant(visualElement, definition);
    let { transitionEnd = {}, transition = {}, ...target2 } = resolved || {};
    target2 = { ...target2, ...transitionEnd };
    for (const key in target2) {
      const value = resolveFinalValueInKeyframes(target2[key]);
      setMotionValue(visualElement, key, value);
    }
  }
  const isMotionValue = (value) => Boolean(value && value.getVelocity);
  function isWillChangeMotionValue(value) {
    return Boolean(isMotionValue(value) && value.add);
  }
  function addValueToWillChange(visualElement, key) {
    const willChange = visualElement.getValue("willChange");
    if (isWillChangeMotionValue(willChange)) {
      return willChange.add(key);
    } else if (!willChange && MotionGlobalConfig.WillChange) {
      const newWillChange = new MotionGlobalConfig.WillChange("auto");
      visualElement.addValue("willChange", newWillChange);
      newWillChange.add(key);
    }
  }
  function camelToDash(str) {
    return str.replace(/([A-Z])/g, (match) => `-${match.toLowerCase()}`);
  }
  const optimizedAppearDataId = "framerAppearId";
  const optimizedAppearDataAttribute = "data-" + camelToDash(optimizedAppearDataId);
  function getOptimisedAppearId(visualElement) {
    return visualElement.props[optimizedAppearDataAttribute];
  }
  function shouldBlockAnimation({ protectedKeys, needsAnimating }, key) {
    const shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true;
    needsAnimating[key] = false;
    return shouldBlock;
  }
  function animateTarget(visualElement, targetAndTransition, { delay: delay2 = 0, transitionOverride, type } = {}) {
    let { transition, transitionEnd, ...target2 } = targetAndTransition;
    const defaultTransition = visualElement.getDefaultTransition();
    transition = transition ? resolveTransition(transition, defaultTransition) : defaultTransition;
    const reduceMotion = transition == null ? void 0 : transition.reduceMotion;
    if (transitionOverride)
      transition = transitionOverride;
    const animations2 = [];
    const animationTypeState = type && visualElement.animationState && visualElement.animationState.getState()[type];
    for (const key in target2) {
      const value = visualElement.getValue(key, visualElement.latestValues[key] ?? null);
      const valueTarget = target2[key];
      if (valueTarget === void 0 || animationTypeState && shouldBlockAnimation(animationTypeState, key)) {
        continue;
      }
      const valueTransition = {
        delay: delay2,
        ...getValueTransition(transition || {}, key)
      };
      const currentValue = value.get();
      if (currentValue !== void 0 && !value.isAnimating() && !Array.isArray(valueTarget) && valueTarget === currentValue && !valueTransition.velocity) {
        frame.update(() => value.set(valueTarget));
        continue;
      }
      let isHandoff = false;
      if (window.MotionHandoffAnimation) {
        const appearId = getOptimisedAppearId(visualElement);
        if (appearId) {
          const startTime = window.MotionHandoffAnimation(appearId, key, frame);
          if (startTime !== null) {
            valueTransition.startTime = startTime;
            isHandoff = true;
          }
        }
      }
      addValueToWillChange(visualElement, key);
      const shouldReduceMotion = reduceMotion ?? visualElement.shouldReduceMotion;
      value.start(animateMotionValue(key, value, valueTarget, shouldReduceMotion && positionalKeys.has(key) ? { type: false } : valueTransition, visualElement, isHandoff));
      const animation = value.animation;
      if (animation) {
        animations2.push(animation);
      }
    }
    if (transitionEnd) {
      const applyTransitionEnd = () => frame.update(() => {
        transitionEnd && setTarget(visualElement, transitionEnd);
      });
      if (animations2.length) {
        Promise.all(animations2).then(applyTransitionEnd);
      } else {
        applyTransitionEnd();
      }
    }
    return animations2;
  }
  function animateVariant(visualElement, variant, options = {}) {
    var _a2;
    const resolved = resolveVariant(visualElement, variant, options.type === "exit" ? (_a2 = visualElement.presenceContext) == null ? void 0 : _a2.custom : void 0);
    let { transition = visualElement.getDefaultTransition() || {} } = resolved || {};
    if (options.transitionOverride) {
      transition = options.transitionOverride;
    }
    const getAnimation = resolved ? () => Promise.all(animateTarget(visualElement, resolved, options)) : () => Promise.resolve();
    const getChildAnimations = visualElement.variantChildren && visualElement.variantChildren.size ? (forwardDelay = 0) => {
      const { delayChildren = 0, staggerChildren, staggerDirection } = transition;
      return animateChildren(visualElement, variant, forwardDelay, delayChildren, staggerChildren, staggerDirection, options);
    } : () => Promise.resolve();
    const { when } = transition;
    if (when) {
      const [first, last] = when === "beforeChildren" ? [getAnimation, getChildAnimations] : [getChildAnimations, getAnimation];
      return first().then(() => last());
    } else {
      return Promise.all([getAnimation(), getChildAnimations(options.delay)]);
    }
  }
  function animateChildren(visualElement, variant, delay2 = 0, delayChildren = 0, staggerChildren = 0, staggerDirection = 1, options) {
    const animations2 = [];
    for (const child of visualElement.variantChildren) {
      child.notify("AnimationStart", variant);
      animations2.push(animateVariant(child, variant, {
        ...options,
        delay: delay2 + (typeof delayChildren === "function" ? 0 : delayChildren) + calcChildStagger(visualElement.variantChildren, child, delayChildren, staggerChildren, staggerDirection)
      }).then(() => child.notify("AnimationComplete", variant)));
    }
    return Promise.all(animations2);
  }
  function animateVisualElement(visualElement, definition, options = {}) {
    visualElement.notify("AnimationStart", definition);
    let animation;
    if (Array.isArray(definition)) {
      const animations2 = definition.map((variant) => animateVariant(visualElement, variant, options));
      animation = Promise.all(animations2);
    } else if (typeof definition === "string") {
      animation = animateVariant(visualElement, definition, options);
    } else {
      const resolvedDefinition = typeof definition === "function" ? resolveVariant(visualElement, definition, options.custom) : definition;
      animation = Promise.all(animateTarget(visualElement, resolvedDefinition, options));
    }
    return animation.then(() => {
      visualElement.notify("AnimationComplete", definition);
    });
  }
  const auto = {
    test: (v) => v === "auto",
    parse: (v) => v
  };
  const testValueType = (v) => (type) => type.test(v);
  const dimensionValueTypes = [number, px, percent, degrees, vw, vh, auto];
  const findDimensionValueType = (v) => dimensionValueTypes.find(testValueType(v));
  function isNone(value) {
    if (typeof value === "number") {
      return value === 0;
    } else if (value !== null) {
      return value === "none" || value === "0" || isZeroValueString(value);
    } else {
      return true;
    }
  }
  const maxDefaults = /* @__PURE__ */ new Set(["brightness", "contrast", "saturate", "opacity"]);
  function applyDefaultFilter(v) {
    const [name2, value] = v.slice(0, -1).split("(");
    if (name2 === "drop-shadow")
      return v;
    const [number2] = value.match(floatRegex) || [];
    if (!number2)
      return v;
    const unit = value.replace(number2, "");
    let defaultValue = maxDefaults.has(name2) ? 1 : 0;
    if (number2 !== value)
      defaultValue *= 100;
    return name2 + "(" + defaultValue + unit + ")";
  }
  const functionRegex = /\b([a-z-]*)\(.*?\)/gu;
  const filter = {
    ...complex,
    getAnimatableNone: (v) => {
      const functions = v.match(functionRegex);
      return functions ? functions.map(applyDefaultFilter).join(" ") : v;
    }
  };
  const mask = {
    ...complex,
    getAnimatableNone: (v) => {
      const parsed = complex.parse(v);
      const transformer = complex.createTransformer(v);
      return transformer(parsed.map((v2) => typeof v2 === "number" ? 0 : typeof v2 === "object" ? { ...v2, alpha: 1 } : v2));
    }
  };
  const int = {
    ...number,
    transform: Math.round
  };
  const transformValueTypes = {
    rotate: degrees,
    rotateX: degrees,
    rotateY: degrees,
    rotateZ: degrees,
    scale,
    scaleX: scale,
    scaleY: scale,
    scaleZ: scale,
    skew: degrees,
    skewX: degrees,
    skewY: degrees,
    distance: px,
    translateX: px,
    translateY: px,
    translateZ: px,
    x: px,
    y: px,
    z: px,
    perspective: px,
    transformPerspective: px,
    opacity: alpha,
    originX: progressPercentage,
    originY: progressPercentage,
    originZ: px
  };
  const numberValueTypes = {
    // Border props
    borderWidth: px,
    borderTopWidth: px,
    borderRightWidth: px,
    borderBottomWidth: px,
    borderLeftWidth: px,
    borderRadius: px,
    borderTopLeftRadius: px,
    borderTopRightRadius: px,
    borderBottomRightRadius: px,
    borderBottomLeftRadius: px,
    // Positioning props
    width: px,
    maxWidth: px,
    height: px,
    maxHeight: px,
    top: px,
    right: px,
    bottom: px,
    left: px,
    inset: px,
    insetBlock: px,
    insetBlockStart: px,
    insetBlockEnd: px,
    insetInline: px,
    insetInlineStart: px,
    insetInlineEnd: px,
    // Spacing props
    padding: px,
    paddingTop: px,
    paddingRight: px,
    paddingBottom: px,
    paddingLeft: px,
    paddingBlock: px,
    paddingBlockStart: px,
    paddingBlockEnd: px,
    paddingInline: px,
    paddingInlineStart: px,
    paddingInlineEnd: px,
    margin: px,
    marginTop: px,
    marginRight: px,
    marginBottom: px,
    marginLeft: px,
    marginBlock: px,
    marginBlockStart: px,
    marginBlockEnd: px,
    marginInline: px,
    marginInlineStart: px,
    marginInlineEnd: px,
    // Typography
    fontSize: px,
    // Misc
    backgroundPositionX: px,
    backgroundPositionY: px,
    ...transformValueTypes,
    zIndex: int,
    // SVG
    fillOpacity: alpha,
    strokeOpacity: alpha,
    numOctaves: int
  };
  const defaultValueTypes = {
    ...numberValueTypes,
    // Color props
    color,
    backgroundColor: color,
    outlineColor: color,
    fill: color,
    stroke: color,
    // Border props
    borderColor: color,
    borderTopColor: color,
    borderRightColor: color,
    borderBottomColor: color,
    borderLeftColor: color,
    filter,
    WebkitFilter: filter,
    mask,
    WebkitMask: mask
  };
  const getDefaultValueType = (key) => defaultValueTypes[key];
  const customTypes = /* @__PURE__ */ new Set([filter, mask]);
  function getAnimatableNone(key, value) {
    let defaultValueType = getDefaultValueType(key);
    if (!customTypes.has(defaultValueType))
      defaultValueType = complex;
    return defaultValueType.getAnimatableNone ? defaultValueType.getAnimatableNone(value) : void 0;
  }
  const invalidTemplates = /* @__PURE__ */ new Set(["auto", "none", "0"]);
  function makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name2) {
    let i = 0;
    let animatableTemplate = void 0;
    while (i < unresolvedKeyframes.length && !animatableTemplate) {
      const keyframe = unresolvedKeyframes[i];
      if (typeof keyframe === "string" && !invalidTemplates.has(keyframe) && analyseComplexValue(keyframe).values.length) {
        animatableTemplate = unresolvedKeyframes[i];
      }
      i++;
    }
    if (animatableTemplate && name2) {
      for (const noneIndex of noneKeyframeIndexes) {
        unresolvedKeyframes[noneIndex] = getAnimatableNone(name2, animatableTemplate);
      }
    }
  }
  class DOMKeyframesResolver extends KeyframeResolver {
    constructor(unresolvedKeyframes, onComplete, name2, motionValue2, element) {
      super(unresolvedKeyframes, onComplete, name2, motionValue2, element, true);
    }
    readKeyframes() {
      const { unresolvedKeyframes, element, name: name2 } = this;
      if (!element || !element.current)
        return;
      super.readKeyframes();
      for (let i = 0; i < unresolvedKeyframes.length; i++) {
        let keyframe = unresolvedKeyframes[i];
        if (typeof keyframe === "string") {
          keyframe = keyframe.trim();
          if (isCSSVariableToken(keyframe)) {
            const resolved = getVariableValue(keyframe, element.current);
            if (resolved !== void 0) {
              unresolvedKeyframes[i] = resolved;
            }
            if (i === unresolvedKeyframes.length - 1) {
              this.finalKeyframe = keyframe;
            }
          }
        }
      }
      this.resolveNoneKeyframes();
      if (!positionalKeys.has(name2) || unresolvedKeyframes.length !== 2) {
        return;
      }
      const [origin, target2] = unresolvedKeyframes;
      const originType = findDimensionValueType(origin);
      const targetType = findDimensionValueType(target2);
      const originHasVar = containsCSSVariable(origin);
      const targetHasVar = containsCSSVariable(target2);
      if (originHasVar !== targetHasVar && positionalValues[name2]) {
        this.needsMeasurement = true;
        return;
      }
      if (originType === targetType)
        return;
      if (isNumOrPxType(originType) && isNumOrPxType(targetType)) {
        for (let i = 0; i < unresolvedKeyframes.length; i++) {
          const value = unresolvedKeyframes[i];
          if (typeof value === "string") {
            unresolvedKeyframes[i] = parseFloat(value);
          }
        }
      } else if (positionalValues[name2]) {
        this.needsMeasurement = true;
      }
    }
    resolveNoneKeyframes() {
      const { unresolvedKeyframes, name: name2 } = this;
      const noneKeyframeIndexes = [];
      for (let i = 0; i < unresolvedKeyframes.length; i++) {
        if (unresolvedKeyframes[i] === null || isNone(unresolvedKeyframes[i])) {
          noneKeyframeIndexes.push(i);
        }
      }
      if (noneKeyframeIndexes.length) {
        makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name2);
      }
    }
    measureInitialState() {
      const { element, unresolvedKeyframes, name: name2 } = this;
      if (!element || !element.current)
        return;
      if (name2 === "height") {
        this.suspendedScrollY = window.pageYOffset;
      }
      this.measuredOrigin = positionalValues[name2](element.measureViewportBox(), window.getComputedStyle(element.current));
      unresolvedKeyframes[0] = this.measuredOrigin;
      const measureKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1];
      if (measureKeyframe !== void 0) {
        element.getValue(name2, measureKeyframe).jump(measureKeyframe, false);
      }
    }
    measureEndState() {
      var _a2;
      const { element, name: name2, unresolvedKeyframes } = this;
      if (!element || !element.current)
        return;
      const value = element.getValue(name2);
      value && value.jump(this.measuredOrigin, false);
      const finalKeyframeIndex = unresolvedKeyframes.length - 1;
      const finalKeyframe = unresolvedKeyframes[finalKeyframeIndex];
      unresolvedKeyframes[finalKeyframeIndex] = positionalValues[name2](element.measureViewportBox(), window.getComputedStyle(element.current));
      if (finalKeyframe !== null && this.finalKeyframe === void 0) {
        this.finalKeyframe = finalKeyframe;
      }
      if ((_a2 = this.removedTransforms) == null ? void 0 : _a2.length) {
        this.removedTransforms.forEach(([unsetTransformName, unsetTransformValue]) => {
          element.getValue(unsetTransformName).set(unsetTransformValue);
        });
      }
      this.resolveNoneKeyframes();
    }
  }
  function resolveElements(elementOrSelector, scope, selectorCache) {
    if (elementOrSelector == null) {
      return [];
    }
    if (elementOrSelector instanceof EventTarget) {
      return [elementOrSelector];
    } else if (typeof elementOrSelector === "string") {
      let root2 = document;
      const elements = root2.querySelectorAll(elementOrSelector);
      return elements ? Array.from(elements) : [];
    }
    return Array.from(elementOrSelector).filter((element) => element != null);
  }
  const getValueAsType = (value, type) => {
    return type && typeof value === "number" ? type.transform(value) : value;
  };
  function isHTMLElement(element) {
    return isObject(element) && "offsetHeight" in element && !("ownerSVGElement" in element);
  }
  const { schedule: microtask } = /* @__PURE__ */ createRenderBatcher(queueMicrotask, false);
  const isDragging = {
    x: false,
    y: false
  };
  function isDragActive() {
    return isDragging.x || isDragging.y;
  }
  function setDragLock(axis) {
    if (axis === "x" || axis === "y") {
      if (isDragging[axis]) {
        return null;
      } else {
        isDragging[axis] = true;
        return () => {
          isDragging[axis] = false;
        };
      }
    } else {
      if (isDragging.x || isDragging.y) {
        return null;
      } else {
        isDragging.x = isDragging.y = true;
        return () => {
          isDragging.x = isDragging.y = false;
        };
      }
    }
  }
  function setupGesture(elementOrSelector, options) {
    const elements = resolveElements(elementOrSelector);
    const gestureAbortController = new AbortController();
    const eventOptions = {
      passive: true,
      ...options,
      signal: gestureAbortController.signal
    };
    const cancel2 = () => gestureAbortController.abort();
    return [elements, eventOptions, cancel2];
  }
  function isValidHover(event) {
    return !(event.pointerType === "touch" || isDragActive());
  }
  function hover(elementOrSelector, onHoverStart, options = {}) {
    const [elements, eventOptions, cancel2] = setupGesture(elementOrSelector, options);
    elements.forEach((element) => {
      let isPressed = false;
      let deferredHoverEnd = false;
      let hoverEndCallback;
      const removePointerLeave = () => {
        element.removeEventListener("pointerleave", onPointerLeave);
      };
      const endHover = (event) => {
        if (hoverEndCallback) {
          hoverEndCallback(event);
          hoverEndCallback = void 0;
        }
        removePointerLeave();
      };
      const onPointerUp = (event) => {
        isPressed = false;
        window.removeEventListener("pointerup", onPointerUp);
        window.removeEventListener("pointercancel", onPointerUp);
        if (deferredHoverEnd) {
          deferredHoverEnd = false;
          endHover(event);
        }
      };
      const onPointerDown = () => {
        isPressed = true;
        window.addEventListener("pointerup", onPointerUp, eventOptions);
        window.addEventListener("pointercancel", onPointerUp, eventOptions);
      };
      const onPointerLeave = (leaveEvent) => {
        if (leaveEvent.pointerType === "touch")
          return;
        if (isPressed) {
          deferredHoverEnd = true;
          return;
        }
        endHover(leaveEvent);
      };
      const onPointerEnter = (enterEvent) => {
        if (!isValidHover(enterEvent))
          return;
        deferredHoverEnd = false;
        const onHoverEnd = onHoverStart(element, enterEvent);
        if (typeof onHoverEnd !== "function")
          return;
        hoverEndCallback = onHoverEnd;
        element.addEventListener("pointerleave", onPointerLeave, eventOptions);
      };
      element.addEventListener("pointerenter", onPointerEnter, eventOptions);
      element.addEventListener("pointerdown", onPointerDown, eventOptions);
    });
    return cancel2;
  }
  const isNodeOrChild = (parent, child) => {
    if (!child) {
      return false;
    } else if (parent === child) {
      return true;
    } else {
      return isNodeOrChild(parent, child.parentElement);
    }
  };
  const isPrimaryPointer = (event) => {
    if (event.pointerType === "mouse") {
      return typeof event.button !== "number" || event.button <= 0;
    } else {
      return event.isPrimary !== false;
    }
  };
  const keyboardAccessibleElements = /* @__PURE__ */ new Set([
    "BUTTON",
    "INPUT",
    "SELECT",
    "TEXTAREA",
    "A"
  ]);
  function isElementKeyboardAccessible(element) {
    return keyboardAccessibleElements.has(element.tagName) || element.isContentEditable === true;
  }
  const textInputElements = /* @__PURE__ */ new Set(["INPUT", "SELECT", "TEXTAREA"]);
  function isElementTextInput(element) {
    return textInputElements.has(element.tagName) || element.isContentEditable === true;
  }
  const isPressing = /* @__PURE__ */ new WeakSet();
  function filterEvents(callback) {
    return (event) => {
      if (event.key !== "Enter")
        return;
      callback(event);
    };
  }
  function firePointerEvent(target2, type) {
    target2.dispatchEvent(new PointerEvent("pointer" + type, { isPrimary: true, bubbles: true }));
  }
  const enableKeyboardPress = (focusEvent, eventOptions) => {
    const element = focusEvent.currentTarget;
    if (!element)
      return;
    const handleKeydown = filterEvents(() => {
      if (isPressing.has(element))
        return;
      firePointerEvent(element, "down");
      const handleKeyup = filterEvents(() => {
        firePointerEvent(element, "up");
      });
      const handleBlur = () => firePointerEvent(element, "cancel");
      element.addEventListener("keyup", handleKeyup, eventOptions);
      element.addEventListener("blur", handleBlur, eventOptions);
    });
    element.addEventListener("keydown", handleKeydown, eventOptions);
    element.addEventListener("blur", () => element.removeEventListener("keydown", handleKeydown), eventOptions);
  };
  function isValidPressEvent(event) {
    return isPrimaryPointer(event) && !isDragActive();
  }
  const claimedPointerDownEvents = /* @__PURE__ */ new WeakSet();
  function press(targetOrSelector, onPressStart, options = {}) {
    const [targets, eventOptions, cancelEvents] = setupGesture(targetOrSelector, options);
    const startPress = (startEvent) => {
      const target2 = startEvent.currentTarget;
      if (!isValidPressEvent(startEvent))
        return;
      if (claimedPointerDownEvents.has(startEvent))
        return;
      isPressing.add(target2);
      if (options.stopPropagation) {
        claimedPointerDownEvents.add(startEvent);
      }
      const onPressEnd = onPressStart(target2, startEvent);
      const onPointerEnd = (endEvent, success) => {
        window.removeEventListener("pointerup", onPointerUp);
        window.removeEventListener("pointercancel", onPointerCancel);
        if (isPressing.has(target2)) {
          isPressing.delete(target2);
        }
        if (!isValidPressEvent(endEvent)) {
          return;
        }
        if (typeof onPressEnd === "function") {
          onPressEnd(endEvent, { success });
        }
      };
      const onPointerUp = (upEvent) => {
        onPointerEnd(upEvent, target2 === window || target2 === document || options.useGlobalTarget || isNodeOrChild(target2, upEvent.target));
      };
      const onPointerCancel = (cancelEvent) => {
        onPointerEnd(cancelEvent, false);
      };
      window.addEventListener("pointerup", onPointerUp, eventOptions);
      window.addEventListener("pointercancel", onPointerCancel, eventOptions);
    };
    targets.forEach((target2) => {
      const pointerDownTarget = options.useGlobalTarget ? window : target2;
      pointerDownTarget.addEventListener("pointerdown", startPress, eventOptions);
      if (isHTMLElement(target2)) {
        target2.addEventListener("focus", (event) => enableKeyboardPress(event, eventOptions));
        if (!isElementKeyboardAccessible(target2) && !target2.hasAttribute("tabindex")) {
          target2.tabIndex = 0;
        }
      }
    });
    return cancelEvents;
  }
  function isSVGElement(element) {
    return isObject(element) && "ownerSVGElement" in element;
  }
  const resizeHandlers = /* @__PURE__ */ new WeakMap();
  let observer;
  const getSize = (borderBoxAxis, svgAxis, htmlAxis) => (target2, borderBoxSize) => {
    if (borderBoxSize && borderBoxSize[0]) {
      return borderBoxSize[0][borderBoxAxis + "Size"];
    } else if (isSVGElement(target2) && "getBBox" in target2) {
      return target2.getBBox()[svgAxis];
    } else {
      return target2[htmlAxis];
    }
  };
  const getWidth = /* @__PURE__ */ getSize("inline", "width", "offsetWidth");
  const getHeight = /* @__PURE__ */ getSize("block", "height", "offsetHeight");
  function notifyTarget({ target: target2, borderBoxSize }) {
    var _a2;
    (_a2 = resizeHandlers.get(target2)) == null ? void 0 : _a2.forEach((handler) => {
      handler(target2, {
        get width() {
          return getWidth(target2, borderBoxSize);
        },
        get height() {
          return getHeight(target2, borderBoxSize);
        }
      });
    });
  }
  function notifyAll(entries) {
    entries.forEach(notifyTarget);
  }
  function createResizeObserver() {
    if (typeof ResizeObserver === "undefined")
      return;
    observer = new ResizeObserver(notifyAll);
  }
  function resizeElement(target2, handler) {
    if (!observer)
      createResizeObserver();
    const elements = resolveElements(target2);
    elements.forEach((element) => {
      let elementHandlers = resizeHandlers.get(element);
      if (!elementHandlers) {
        elementHandlers = /* @__PURE__ */ new Set();
        resizeHandlers.set(element, elementHandlers);
      }
      elementHandlers.add(handler);
      observer == null ? void 0 : observer.observe(element);
    });
    return () => {
      elements.forEach((element) => {
        const elementHandlers = resizeHandlers.get(element);
        elementHandlers == null ? void 0 : elementHandlers.delete(handler);
        if (!(elementHandlers == null ? void 0 : elementHandlers.size)) {
          observer == null ? void 0 : observer.unobserve(element);
        }
      });
    };
  }
  const windowCallbacks = /* @__PURE__ */ new Set();
  let windowResizeHandler;
  function createWindowResizeHandler() {
    windowResizeHandler = () => {
      const info = {
        get width() {
          return window.innerWidth;
        },
        get height() {
          return window.innerHeight;
        }
      };
      windowCallbacks.forEach((callback) => callback(info));
    };
    window.addEventListener("resize", windowResizeHandler);
  }
  function resizeWindow(callback) {
    windowCallbacks.add(callback);
    if (!windowResizeHandler)
      createWindowResizeHandler();
    return () => {
      windowCallbacks.delete(callback);
      if (!windowCallbacks.size && typeof windowResizeHandler === "function") {
        window.removeEventListener("resize", windowResizeHandler);
        windowResizeHandler = void 0;
      }
    };
  }
  function resize(a, b) {
    return typeof a === "function" ? resizeWindow(a) : resizeElement(a, b);
  }
  function isSVGSVGElement(element) {
    return isSVGElement(element) && element.tagName === "svg";
  }
  function transform(...args) {
    const useImmediate = !Array.isArray(args[0]);
    const argOffset = useImmediate ? 0 : -1;
    const inputValue = args[0 + argOffset];
    const inputRange = args[1 + argOffset];
    const outputRange = args[2 + argOffset];
    const options = args[3 + argOffset];
    const interpolator = interpolate(inputRange, outputRange, options);
    return useImmediate ? interpolator(inputValue) : interpolator;
  }
  function attachFollow(value, source, options = {}) {
    const initialValue = value.get();
    let activeAnimation = null;
    let latestValue = initialValue;
    let latestSetter;
    const unit = typeof initialValue === "string" ? initialValue.replace(/[\d.-]/g, "") : void 0;
    const stopAnimation = () => {
      if (activeAnimation) {
        activeAnimation.stop();
        activeAnimation = null;
      }
      value.animation = void 0;
    };
    const startAnimation = () => {
      const currentValue = asNumber$1(value.get());
      const targetValue = asNumber$1(latestValue);
      if (currentValue === targetValue) {
        stopAnimation();
        return;
      }
      const velocity = activeAnimation ? activeAnimation.getGeneratorVelocity() : value.getVelocity();
      stopAnimation();
      activeAnimation = new JSAnimation({
        keyframes: [currentValue, targetValue],
        velocity,
        // Default to spring if no type specified (matches useSpring behavior)
        type: "spring",
        restDelta: 1e-3,
        restSpeed: 0.01,
        ...options,
        onUpdate: latestSetter
      });
    };
    const scheduleAnimation = () => {
      var _a2;
      startAnimation();
      value.animation = activeAnimation ?? void 0;
      (_a2 = value["events"].animationStart) == null ? void 0 : _a2.notify();
      activeAnimation == null ? void 0 : activeAnimation.then(() => {
        var _a3;
        value.animation = void 0;
        (_a3 = value["events"].animationComplete) == null ? void 0 : _a3.notify();
      });
    };
    value.attach((v, set) => {
      latestValue = v;
      latestSetter = (latest) => set(parseValue(latest, unit));
      frame.postRender(scheduleAnimation);
    }, stopAnimation);
    if (isMotionValue(source)) {
      let skipNextAnimation = options.skipInitialAnimation === true;
      const removeSourceOnChange = source.on("change", (v) => {
        if (skipNextAnimation) {
          skipNextAnimation = false;
          value.jump(parseValue(v, unit), false);
        } else {
          value.set(parseValue(v, unit));
        }
      });
      const removeValueOnDestroy = value.on("destroy", removeSourceOnChange);
      return () => {
        removeSourceOnChange();
        removeValueOnDestroy();
      };
    }
    return stopAnimation;
  }
  function parseValue(v, unit) {
    return unit ? v + unit : v;
  }
  function asNumber$1(v) {
    return typeof v === "number" ? v : parseFloat(v);
  }
  const valueTypes = [...dimensionValueTypes, color, complex];
  const findValueType = (v) => valueTypes.find(testValueType(v));
  const createAxisDelta = () => ({
    translate: 0,
    scale: 1,
    origin: 0,
    originPoint: 0
  });
  const createDelta = () => ({
    x: createAxisDelta(),
    y: createAxisDelta()
  });
  const createAxis = () => ({ min: 0, max: 0 });
  const createBox = () => ({
    x: createAxis(),
    y: createAxis()
  });
  const visualElementStore = /* @__PURE__ */ new WeakMap();
  function isAnimationControls(v) {
    return v !== null && typeof v === "object" && typeof v.start === "function";
  }
  function isVariantLabel(v) {
    return typeof v === "string" || Array.isArray(v);
  }
  const variantPriorityOrder = [
    "animate",
    "whileInView",
    "whileFocus",
    "whileHover",
    "whileTap",
    "whileDrag",
    "exit"
  ];
  const variantProps = ["initial", ...variantPriorityOrder];
  function isControllingVariants(props) {
    return isAnimationControls(props.animate) || variantProps.some((name2) => isVariantLabel(props[name2]));
  }
  function isVariantNode(props) {
    return Boolean(isControllingVariants(props) || props.variants);
  }
  function updateMotionValuesFromProps(element, next, prev) {
    for (const key in next) {
      const nextValue = next[key];
      const prevValue = prev[key];
      if (isMotionValue(nextValue)) {
        element.addValue(key, nextValue);
      } else if (isMotionValue(prevValue)) {
        element.addValue(key, motionValue(nextValue, { owner: element }));
      } else if (prevValue !== nextValue) {
        if (element.hasValue(key)) {
          const existingValue = element.getValue(key);
          if (existingValue.liveStyle === true) {
            existingValue.jump(nextValue);
          } else if (!existingValue.hasAnimated) {
            existingValue.set(nextValue);
          }
        } else {
          const latestValue = element.getStaticValue(key);
          element.addValue(key, motionValue(latestValue !== void 0 ? latestValue : nextValue, { owner: element }));
        }
      }
    }
    for (const key in prev) {
      if (next[key] === void 0)
        element.removeValue(key);
    }
    return next;
  }
  const prefersReducedMotion = { current: null };
  const hasReducedMotionListener = { current: false };
  const isBrowser = typeof window !== "undefined";
  function initPrefersReducedMotion() {
    hasReducedMotionListener.current = true;
    if (!isBrowser)
      return;
    if (window.matchMedia) {
      const motionMediaQuery = window.matchMedia("(prefers-reduced-motion)");
      const setReducedMotionPreferences = () => prefersReducedMotion.current = motionMediaQuery.matches;
      motionMediaQuery.addEventListener("change", setReducedMotionPreferences);
      setReducedMotionPreferences();
    } else {
      prefersReducedMotion.current = false;
    }
  }
  const propEventHandlers = [
    "AnimationStart",
    "AnimationComplete",
    "Update",
    "BeforeLayoutMeasure",
    "LayoutMeasure",
    "LayoutAnimationStart",
    "LayoutAnimationComplete"
  ];
  let featureDefinitions = {};
  function setFeatureDefinitions(definitions) {
    featureDefinitions = definitions;
  }
  function getFeatureDefinitions() {
    return featureDefinitions;
  }
  class VisualElement {
    /**
     * This method takes React props and returns found MotionValues. For example, HTML
     * MotionValues will be found within the style prop, whereas for Three.js within attribute arrays.
     *
     * This isn't an abstract method as it needs calling in the constructor, but it is
     * intended to be one.
     */
    scrapeMotionValuesFromProps(_props, _prevProps, _visualElement) {
      return {};
    }
    constructor({ parent, props, presenceContext, reducedMotionConfig, skipAnimations, blockInitialAnimation, visualState }, options = {}) {
      this.current = null;
      this.children = /* @__PURE__ */ new Set();
      this.isVariantNode = false;
      this.isControllingVariants = false;
      this.shouldReduceMotion = null;
      this.shouldSkipAnimations = false;
      this.values = /* @__PURE__ */ new Map();
      this.KeyframeResolver = KeyframeResolver;
      this.features = {};
      this.valueSubscriptions = /* @__PURE__ */ new Map();
      this.prevMotionValues = {};
      this.hasBeenMounted = false;
      this.events = {};
      this.propEventSubscriptions = {};
      this.notifyUpdate = () => this.notify("Update", this.latestValues);
      this.render = () => {
        if (!this.current)
          return;
        this.triggerBuild();
        this.renderInstance(this.current, this.renderState, this.props.style, this.projection);
      };
      this.renderScheduledAt = 0;
      this.scheduleRender = () => {
        const now2 = time.now();
        if (this.renderScheduledAt < now2) {
          this.renderScheduledAt = now2;
          frame.render(this.render, false, true);
        }
      };
      const { latestValues, renderState } = visualState;
      this.latestValues = latestValues;
      this.baseTarget = { ...latestValues };
      this.initialValues = props.initial ? { ...latestValues } : {};
      this.renderState = renderState;
      this.parent = parent;
      this.props = props;
      this.presenceContext = presenceContext;
      this.depth = parent ? parent.depth + 1 : 0;
      this.reducedMotionConfig = reducedMotionConfig;
      this.skipAnimationsConfig = skipAnimations;
      this.options = options;
      this.blockInitialAnimation = Boolean(blockInitialAnimation);
      this.isControllingVariants = isControllingVariants(props);
      this.isVariantNode = isVariantNode(props);
      if (this.isVariantNode) {
        this.variantChildren = /* @__PURE__ */ new Set();
      }
      this.manuallyAnimateOnMount = Boolean(parent && parent.current);
      const { willChange, ...initialMotionValues } = this.scrapeMotionValuesFromProps(props, {}, this);
      for (const key in initialMotionValues) {
        const value = initialMotionValues[key];
        if (latestValues[key] !== void 0 && isMotionValue(value)) {
          value.set(latestValues[key]);
        }
      }
    }
    mount(instance) {
      var _a2, _b;
      if (this.hasBeenMounted) {
        for (const key in this.initialValues) {
          (_a2 = this.values.get(key)) == null ? void 0 : _a2.jump(this.initialValues[key]);
          this.latestValues[key] = this.initialValues[key];
        }
      }
      this.current = instance;
      visualElementStore.set(instance, this);
      if (this.projection && !this.projection.instance) {
        this.projection.mount(instance);
      }
      if (this.parent && this.isVariantNode && !this.isControllingVariants) {
        this.removeFromVariantTree = this.parent.addVariantChild(this);
      }
      this.values.forEach((value, key) => this.bindToMotionValue(key, value));
      if (this.reducedMotionConfig === "never") {
        this.shouldReduceMotion = false;
      } else if (this.reducedMotionConfig === "always") {
        this.shouldReduceMotion = true;
      } else {
        if (!hasReducedMotionListener.current) {
          initPrefersReducedMotion();
        }
        this.shouldReduceMotion = prefersReducedMotion.current;
      }
      this.shouldSkipAnimations = this.skipAnimationsConfig ?? false;
      (_b = this.parent) == null ? void 0 : _b.addChild(this);
      this.update(this.props, this.presenceContext);
      this.hasBeenMounted = true;
    }
    unmount() {
      var _a2;
      this.projection && this.projection.unmount();
      cancelFrame(this.notifyUpdate);
      cancelFrame(this.render);
      this.valueSubscriptions.forEach((remove) => remove());
      this.valueSubscriptions.clear();
      this.removeFromVariantTree && this.removeFromVariantTree();
      (_a2 = this.parent) == null ? void 0 : _a2.removeChild(this);
      for (const key in this.events) {
        this.events[key].clear();
      }
      for (const key in this.features) {
        const feature = this.features[key];
        if (feature) {
          feature.unmount();
          feature.isMounted = false;
        }
      }
      this.current = null;
    }
    addChild(child) {
      this.children.add(child);
      this.enteringChildren ?? (this.enteringChildren = /* @__PURE__ */ new Set());
      this.enteringChildren.add(child);
    }
    removeChild(child) {
      this.children.delete(child);
      this.enteringChildren && this.enteringChildren.delete(child);
    }
    bindToMotionValue(key, value) {
      if (this.valueSubscriptions.has(key)) {
        this.valueSubscriptions.get(key)();
      }
      if (value.accelerate && acceleratedValues.has(key) && this.current instanceof HTMLElement) {
        const { factory, keyframes: keyframes2, times, ease: ease2, duration } = value.accelerate;
        const animation = new NativeAnimation({
          element: this.current,
          name: key,
          keyframes: keyframes2,
          times,
          ease: ease2,
          duration: /* @__PURE__ */ secondsToMilliseconds(duration)
        });
        const cleanup = factory(animation);
        this.valueSubscriptions.set(key, () => {
          cleanup();
          animation.cancel();
        });
        return;
      }
      const valueIsTransform = transformProps.has(key);
      if (valueIsTransform && this.onBindTransform) {
        this.onBindTransform();
      }
      const removeOnChange = value.on("change", (latestValue) => {
        this.latestValues[key] = latestValue;
        this.props.onUpdate && frame.preRender(this.notifyUpdate);
        if (valueIsTransform && this.projection) {
          this.projection.isTransformDirty = true;
        }
        this.scheduleRender();
      });
      let removeSyncCheck;
      if (typeof window !== "undefined" && window.MotionCheckAppearSync) {
        removeSyncCheck = window.MotionCheckAppearSync(this, key, value);
      }
      this.valueSubscriptions.set(key, () => {
        removeOnChange();
        if (removeSyncCheck)
          removeSyncCheck();
        if (value.owner)
          value.stop();
      });
    }
    sortNodePosition(other) {
      if (!this.current || !this.sortInstanceNodePosition || this.type !== other.type) {
        return 0;
      }
      return this.sortInstanceNodePosition(this.current, other.current);
    }
    updateFeatures() {
      let key = "animation";
      for (key in featureDefinitions) {
        const featureDefinition = featureDefinitions[key];
        if (!featureDefinition)
          continue;
        const { isEnabled, Feature: FeatureConstructor } = featureDefinition;
        if (!this.features[key] && FeatureConstructor && isEnabled(this.props)) {
          this.features[key] = new FeatureConstructor(this);
        }
        if (this.features[key]) {
          const feature = this.features[key];
          if (feature.isMounted) {
            feature.update();
          } else {
            feature.mount();
            feature.isMounted = true;
          }
        }
      }
    }
    triggerBuild() {
      this.build(this.renderState, this.latestValues, this.props);
    }
    /**
     * Measure the current viewport box with or without transforms.
     * Only measures axis-aligned boxes, rotate and skew must be manually
     * removed with a re-render to work.
     */
    measureViewportBox() {
      return this.current ? this.measureInstanceViewportBox(this.current, this.props) : createBox();
    }
    getStaticValue(key) {
      return this.latestValues[key];
    }
    setStaticValue(key, value) {
      this.latestValues[key] = value;
    }
    /**
     * Update the provided props. Ensure any newly-added motion values are
     * added to our map, old ones removed, and listeners updated.
     */
    update(props, presenceContext) {
      if (props.transformTemplate || this.props.transformTemplate) {
        this.scheduleRender();
      }
      this.prevProps = this.props;
      this.props = props;
      this.prevPresenceContext = this.presenceContext;
      this.presenceContext = presenceContext;
      for (let i = 0; i < propEventHandlers.length; i++) {
        const key = propEventHandlers[i];
        if (this.propEventSubscriptions[key]) {
          this.propEventSubscriptions[key]();
          delete this.propEventSubscriptions[key];
        }
        const listenerName = "on" + key;
        const listener = props[listenerName];
        if (listener) {
          this.propEventSubscriptions[key] = this.on(key, listener);
        }
      }
      this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props, this.prevProps || {}, this), this.prevMotionValues);
      if (this.handleChildMotionValue) {
        this.handleChildMotionValue();
      }
    }
    getProps() {
      return this.props;
    }
    /**
     * Returns the variant definition with a given name.
     */
    getVariant(name2) {
      return this.props.variants ? this.props.variants[name2] : void 0;
    }
    /**
     * Returns the defined default transition on this component.
     */
    getDefaultTransition() {
      return this.props.transition;
    }
    getTransformPagePoint() {
      return this.props.transformPagePoint;
    }
    getClosestVariantNode() {
      return this.isVariantNode ? this : this.parent ? this.parent.getClosestVariantNode() : void 0;
    }
    /**
     * Add a child visual element to our set of children.
     */
    addVariantChild(child) {
      const closestVariantNode = this.getClosestVariantNode();
      if (closestVariantNode) {
        closestVariantNode.variantChildren && closestVariantNode.variantChildren.add(child);
        return () => closestVariantNode.variantChildren.delete(child);
      }
    }
    /**
     * Add a motion value and bind it to this visual element.
     */
    addValue(key, value) {
      const existingValue = this.values.get(key);
      if (value !== existingValue) {
        if (existingValue)
          this.removeValue(key);
        this.bindToMotionValue(key, value);
        this.values.set(key, value);
        this.latestValues[key] = value.get();
      }
    }
    /**
     * Remove a motion value and unbind any active subscriptions.
     */
    removeValue(key) {
      this.values.delete(key);
      const unsubscribe = this.valueSubscriptions.get(key);
      if (unsubscribe) {
        unsubscribe();
        this.valueSubscriptions.delete(key);
      }
      delete this.latestValues[key];
      this.removeValueFromRenderState(key, this.renderState);
    }
    /**
     * Check whether we have a motion value for this key
     */
    hasValue(key) {
      return this.values.has(key);
    }
    getValue(key, defaultValue) {
      if (this.props.values && this.props.values[key]) {
        return this.props.values[key];
      }
      let value = this.values.get(key);
      if (value === void 0 && defaultValue !== void 0) {
        value = motionValue(defaultValue === null ? void 0 : defaultValue, { owner: this });
        this.addValue(key, value);
      }
      return value;
    }
    /**
     * If we're trying to animate to a previously unencountered value,
     * we need to check for it in our state and as a last resort read it
     * directly from the instance (which might have performance implications).
     */
    readValue(key, target2) {
      let value = this.latestValues[key] !== void 0 || !this.current ? this.latestValues[key] : this.getBaseTargetFromProps(this.props, key) ?? this.readValueFromInstance(this.current, key, this.options);
      if (value !== void 0 && value !== null) {
        if (typeof value === "string" && (isNumericalString(value) || isZeroValueString(value))) {
          value = parseFloat(value);
        } else if (!findValueType(value) && complex.test(target2)) {
          value = getAnimatableNone(key, target2);
        }
        this.setBaseTarget(key, isMotionValue(value) ? value.get() : value);
      }
      return isMotionValue(value) ? value.get() : value;
    }
    /**
     * Set the base target to later animate back to. This is currently
     * only hydrated on creation and when we first read a value.
     */
    setBaseTarget(key, value) {
      this.baseTarget[key] = value;
    }
    /**
     * Find the base target for a value thats been removed from all animation
     * props.
     */
    getBaseTarget(key) {
      var _a2;
      const { initial } = this.props;
      let valueFromInitial;
      if (typeof initial === "string" || typeof initial === "object") {
        const variant = resolveVariantFromProps(this.props, initial, (_a2 = this.presenceContext) == null ? void 0 : _a2.custom);
        if (variant) {
          valueFromInitial = variant[key];
        }
      }
      if (initial && valueFromInitial !== void 0) {
        return valueFromInitial;
      }
      const target2 = this.getBaseTargetFromProps(this.props, key);
      if (target2 !== void 0 && !isMotionValue(target2))
        return target2;
      return this.initialValues[key] !== void 0 && valueFromInitial === void 0 ? void 0 : this.baseTarget[key];
    }
    on(eventName, callback) {
      if (!this.events[eventName]) {
        this.events[eventName] = new SubscriptionManager();
      }
      return this.events[eventName].add(callback);
    }
    notify(eventName, ...args) {
      if (this.events[eventName]) {
        this.events[eventName].notify(...args);
      }
    }
    scheduleRenderMicrotask() {
      microtask.render(this.render);
    }
  }
  class DOMVisualElement extends VisualElement {
    constructor() {
      super(...arguments);
      this.KeyframeResolver = DOMKeyframesResolver;
    }
    sortInstanceNodePosition(a, b) {
      return a.compareDocumentPosition(b) & 2 ? 1 : -1;
    }
    getBaseTargetFromProps(props, key) {
      const style = props.style;
      return style ? style[key] : void 0;
    }
    removeValueFromRenderState(key, { vars, style }) {
      delete vars[key];
      delete style[key];
    }
    handleChildMotionValue() {
      if (this.childSubscription) {
        this.childSubscription();
        delete this.childSubscription;
      }
      const { children } = this.props;
      if (isMotionValue(children)) {
        this.childSubscription = children.on("change", (latest) => {
          if (this.current) {
            this.current.textContent = `${latest}`;
          }
        });
      }
    }
  }
  class Feature {
    constructor(node) {
      this.isMounted = false;
      this.node = node;
    }
    update() {
    }
  }
  function convertBoundingBoxToBox({ top, left, right, bottom }) {
    return {
      x: { min: left, max: right },
      y: { min: top, max: bottom }
    };
  }
  function convertBoxToBoundingBox({ x, y }) {
    return { top: y.min, right: x.max, bottom: y.max, left: x.min };
  }
  function transformBoxPoints(point, transformPoint2) {
    if (!transformPoint2)
      return point;
    const topLeft = transformPoint2({ x: point.left, y: point.top });
    const bottomRight = transformPoint2({ x: point.right, y: point.bottom });
    return {
      top: topLeft.y,
      left: topLeft.x,
      bottom: bottomRight.y,
      right: bottomRight.x
    };
  }
  function isIdentityScale(scale2) {
    return scale2 === void 0 || scale2 === 1;
  }
  function hasScale({ scale: scale2, scaleX: scaleX2, scaleY: scaleY2 }) {
    return !isIdentityScale(scale2) || !isIdentityScale(scaleX2) || !isIdentityScale(scaleY2);
  }
  function hasTransform(values) {
    return hasScale(values) || has2DTranslate(values) || values.z || values.rotate || values.rotateX || values.rotateY || values.skewX || values.skewY;
  }
  function has2DTranslate(values) {
    return is2DTranslate(values.x) || is2DTranslate(values.y);
  }
  function is2DTranslate(value) {
    return value && value !== "0%";
  }
  function scalePoint(point, scale2, originPoint) {
    const distanceFromOrigin = point - originPoint;
    const scaled = scale2 * distanceFromOrigin;
    return originPoint + scaled;
  }
  function applyPointDelta(point, translate, scale2, originPoint, boxScale) {
    if (boxScale !== void 0) {
      point = scalePoint(point, boxScale, originPoint);
    }
    return scalePoint(point, scale2, originPoint) + translate;
  }
  function applyAxisDelta(axis, translate = 0, scale2 = 1, originPoint, boxScale) {
    axis.min = applyPointDelta(axis.min, translate, scale2, originPoint, boxScale);
    axis.max = applyPointDelta(axis.max, translate, scale2, originPoint, boxScale);
  }
  function applyBoxDelta(box, { x, y }) {
    applyAxisDelta(box.x, x.translate, x.scale, x.originPoint);
    applyAxisDelta(box.y, y.translate, y.scale, y.originPoint);
  }
  const TREE_SCALE_SNAP_MIN = 0.999999999999;
  const TREE_SCALE_SNAP_MAX = 1.0000000000001;
  function applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) {
    var _a2;
    const treeLength = treePath.length;
    if (!treeLength)
      return;
    treeScale.x = treeScale.y = 1;
    let node;
    let delta;
    for (let i = 0; i < treeLength; i++) {
      node = treePath[i];
      delta = node.projectionDelta;
      const { visualElement } = node.options;
      if (visualElement && visualElement.props.style && visualElement.props.style.display === "contents") {
        continue;
      }
      if (isSharedTransition && node.options.layoutScroll && node.scroll && node !== node.root) {
        translateAxis(box.x, -node.scroll.offset.x);
        translateAxis(box.y, -node.scroll.offset.y);
      }
      if (delta) {
        treeScale.x *= delta.x.scale;
        treeScale.y *= delta.y.scale;
        applyBoxDelta(box, delta);
      }
      if (isSharedTransition && hasTransform(node.latestValues)) {
        transformBox(box, node.latestValues, (_a2 = node.layout) == null ? void 0 : _a2.layoutBox);
      }
    }
    if (treeScale.x < TREE_SCALE_SNAP_MAX && treeScale.x > TREE_SCALE_SNAP_MIN) {
      treeScale.x = 1;
    }
    if (treeScale.y < TREE_SCALE_SNAP_MAX && treeScale.y > TREE_SCALE_SNAP_MIN) {
      treeScale.y = 1;
    }
  }
  function translateAxis(axis, distance2) {
    axis.min += distance2;
    axis.max += distance2;
  }
  function transformAxis(axis, axisTranslate, axisScale, boxScale, axisOrigin = 0.5) {
    const originPoint = mixNumber$1(axis.min, axis.max, axisOrigin);
    applyAxisDelta(axis, axisTranslate, axisScale, originPoint, boxScale);
  }
  function resolveAxisTranslate(value, axis) {
    if (typeof value === "string") {
      return parseFloat(value) / 100 * (axis.max - axis.min);
    }
    return value;
  }
  function transformBox(box, transform2, sourceBox) {
    const resolveBox = sourceBox ?? box;
    transformAxis(box.x, resolveAxisTranslate(transform2.x, resolveBox.x), transform2.scaleX, transform2.scale, transform2.originX);
    transformAxis(box.y, resolveAxisTranslate(transform2.y, resolveBox.y), transform2.scaleY, transform2.scale, transform2.originY);
  }
  function measureViewportBox(instance, transformPoint2) {
    return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint2));
  }
  function measurePageBox(element, rootProjectionNode2, transformPagePoint) {
    const viewportBox = measureViewportBox(element, transformPagePoint);
    const { scroll } = rootProjectionNode2;
    if (scroll) {
      translateAxis(viewportBox.x, scroll.offset.x);
      translateAxis(viewportBox.y, scroll.offset.y);
    }
    return viewportBox;
  }
  const translateAlias = {
    x: "translateX",
    y: "translateY",
    z: "translateZ",
    transformPerspective: "perspective"
  };
  const numTransforms = transformPropOrder.length;
  function buildTransform(latestValues, transform2, transformTemplate) {
    let transformString = "";
    let transformIsDefault = true;
    for (let i = 0; i < numTransforms; i++) {
      const key = transformPropOrder[i];
      const value = latestValues[key];
      if (value === void 0)
        continue;
      let valueIsDefault = true;
      if (typeof value === "number") {
        valueIsDefault = value === (key.startsWith("scale") ? 1 : 0);
      } else {
        const parsed = parseFloat(value);
        valueIsDefault = key.startsWith("scale") ? parsed === 1 : parsed === 0;
      }
      if (!valueIsDefault || transformTemplate) {
        const valueAsType = getValueAsType(value, numberValueTypes[key]);
        if (!valueIsDefault) {
          transformIsDefault = false;
          const transformName = translateAlias[key] || key;
          transformString += `${transformName}(${valueAsType}) `;
        }
        if (transformTemplate) {
          transform2[key] = valueAsType;
        }
      }
    }
    transformString = transformString.trim();
    if (transformTemplate) {
      transformString = transformTemplate(transform2, transformIsDefault ? "" : transformString);
    } else if (transformIsDefault) {
      transformString = "none";
    }
    return transformString;
  }
  function buildHTMLStyles(state, latestValues, transformTemplate) {
    const { style, vars, transformOrigin } = state;
    let hasTransform2 = false;
    let hasTransformOrigin = false;
    for (const key in latestValues) {
      const value = latestValues[key];
      if (transformProps.has(key)) {
        hasTransform2 = true;
        continue;
      } else if (isCSSVariableName(key)) {
        vars[key] = value;
        continue;
      } else {
        const valueAsType = getValueAsType(value, numberValueTypes[key]);
        if (key.startsWith("origin")) {
          hasTransformOrigin = true;
          transformOrigin[key] = valueAsType;
        } else {
          style[key] = valueAsType;
        }
      }
    }
    if (!latestValues.transform) {
      if (hasTransform2 || transformTemplate) {
        style.transform = buildTransform(latestValues, state.transform, transformTemplate);
      } else if (style.transform) {
        style.transform = "none";
      }
    }
    if (hasTransformOrigin) {
      const { originX = "50%", originY = "50%", originZ = 0 } = transformOrigin;
      style.transformOrigin = `${originX} ${originY} ${originZ}`;
    }
  }
  function renderHTML(element, { style, vars }, styleProp, projection) {
    const elementStyle = element.style;
    let key;
    for (key in style) {
      elementStyle[key] = style[key];
    }
    projection == null ? void 0 : projection.applyProjectionStyles(elementStyle, styleProp);
    for (key in vars) {
      elementStyle.setProperty(key, vars[key]);
    }
  }
  function pixelsToPercent(pixels, axis) {
    if (axis.max === axis.min)
      return 0;
    return pixels / (axis.max - axis.min) * 100;
  }
  const correctBorderRadius = {
    correct: (latest, node) => {
      if (!node.target)
        return latest;
      if (typeof latest === "string") {
        if (px.test(latest)) {
          latest = parseFloat(latest);
        } else {
          return latest;
        }
      }
      const x = pixelsToPercent(latest, node.target.x);
      const y = pixelsToPercent(latest, node.target.y);
      return `${x}% ${y}%`;
    }
  };
  const correctBoxShadow = {
    correct: (latest, { treeScale, projectionDelta }) => {
      const original = latest;
      const shadow = complex.parse(latest);
      if (shadow.length > 5)
        return original;
      const template = complex.createTransformer(latest);
      const offset = typeof shadow[0] !== "number" ? 1 : 0;
      const xScale = projectionDelta.x.scale * treeScale.x;
      const yScale = projectionDelta.y.scale * treeScale.y;
      shadow[0 + offset] /= xScale;
      shadow[1 + offset] /= yScale;
      const averageScale = mixNumber$1(xScale, yScale, 0.5);
      if (typeof shadow[2 + offset] === "number")
        shadow[2 + offset] /= averageScale;
      if (typeof shadow[3 + offset] === "number")
        shadow[3 + offset] /= averageScale;
      return template(shadow);
    }
  };
  const scaleCorrectors = {
    borderRadius: {
      ...correctBorderRadius,
      applyTo: [
        "borderTopLeftRadius",
        "borderTopRightRadius",
        "borderBottomLeftRadius",
        "borderBottomRightRadius"
      ]
    },
    borderTopLeftRadius: correctBorderRadius,
    borderTopRightRadius: correctBorderRadius,
    borderBottomLeftRadius: correctBorderRadius,
    borderBottomRightRadius: correctBorderRadius,
    boxShadow: correctBoxShadow
  };
  function isForcedMotionValue(key, { layout: layout2, layoutId }) {
    return transformProps.has(key) || key.startsWith("origin") || (layout2 || layoutId !== void 0) && (!!scaleCorrectors[key] || key === "opacity");
  }
  function scrapeMotionValuesFromProps$1(props, prevProps, visualElement) {
    var _a2;
    const style = props.style;
    const prevStyle = prevProps == null ? void 0 : prevProps.style;
    const newValues = {};
    if (!style)
      return newValues;
    for (const key in style) {
      if (isMotionValue(style[key]) || prevStyle && isMotionValue(prevStyle[key]) || isForcedMotionValue(key, props) || ((_a2 = visualElement == null ? void 0 : visualElement.getValue(key)) == null ? void 0 : _a2.liveStyle) !== void 0) {
        newValues[key] = style[key];
      }
    }
    return newValues;
  }
  function getComputedStyle$1(element) {
    return window.getComputedStyle(element);
  }
  class HTMLVisualElement extends DOMVisualElement {
    constructor() {
      super(...arguments);
      this.type = "html";
      this.renderInstance = renderHTML;
    }
    readValueFromInstance(instance, key) {
      var _a2;
      if (transformProps.has(key)) {
        return ((_a2 = this.projection) == null ? void 0 : _a2.isProjecting) ? defaultTransformValue(key) : readTransformValue(instance, key);
      } else {
        const computedStyle = getComputedStyle$1(instance);
        const value = (isCSSVariableName(key) ? computedStyle.getPropertyValue(key) : computedStyle[key]) || 0;
        return typeof value === "string" ? value.trim() : value;
      }
    }
    measureInstanceViewportBox(instance, { transformPagePoint }) {
      return measureViewportBox(instance, transformPagePoint);
    }
    build(renderState, latestValues, props) {
      buildHTMLStyles(renderState, latestValues, props.transformTemplate);
    }
    scrapeMotionValuesFromProps(props, prevProps, visualElement) {
      return scrapeMotionValuesFromProps$1(props, prevProps, visualElement);
    }
  }
  const dashKeys = {
    offset: "stroke-dashoffset",
    array: "stroke-dasharray"
  };
  const camelKeys = {
    offset: "strokeDashoffset",
    array: "strokeDasharray"
  };
  function buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true) {
    attrs.pathLength = 1;
    const keys = useDashCase ? dashKeys : camelKeys;
    attrs[keys.offset] = `${-offset}`;
    attrs[keys.array] = `${length} ${spacing}`;
  }
  const cssMotionPathProperties = [
    "offsetDistance",
    "offsetPath",
    "offsetRotate",
    "offsetAnchor"
  ];
  function buildSVGAttrs(state, {
    attrX,
    attrY,
    attrScale,
    pathLength,
    pathSpacing = 1,
    pathOffset = 0,
    // This is object creation, which we try to avoid per-frame.
    ...latest
  }, isSVGTag2, transformTemplate, styleProp) {
    buildHTMLStyles(state, latest, transformTemplate);
    if (isSVGTag2) {
      if (state.style.viewBox) {
        state.attrs.viewBox = state.style.viewBox;
      }
      return;
    }
    state.attrs = state.style;
    state.style = {};
    const { attrs, style } = state;
    if (attrs.transform) {
      style.transform = attrs.transform;
      delete attrs.transform;
    }
    if (style.transform || attrs.transformOrigin) {
      style.transformOrigin = attrs.transformOrigin ?? "50% 50%";
      delete attrs.transformOrigin;
    }
    if (style.transform) {
      style.transformBox = (styleProp == null ? void 0 : styleProp.transformBox) ?? "fill-box";
      delete attrs.transformBox;
    }
    for (const key of cssMotionPathProperties) {
      if (attrs[key] !== void 0) {
        style[key] = attrs[key];
        delete attrs[key];
      }
    }
    if (attrX !== void 0)
      attrs.x = attrX;
    if (attrY !== void 0)
      attrs.y = attrY;
    if (attrScale !== void 0)
      attrs.scale = attrScale;
    if (pathLength !== void 0) {
      buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false);
    }
  }
  const camelCaseAttributes = /* @__PURE__ */ new Set([
    "baseFrequency",
    "diffuseConstant",
    "kernelMatrix",
    "kernelUnitLength",
    "keySplines",
    "keyTimes",
    "limitingConeAngle",
    "markerHeight",
    "markerWidth",
    "numOctaves",
    "targetX",
    "targetY",
    "surfaceScale",
    "specularConstant",
    "specularExponent",
    "stdDeviation",
    "tableValues",
    "viewBox",
    "gradientTransform",
    "pathLength",
    "startOffset",
    "textLength",
    "lengthAdjust"
  ]);
  const isSVGTag = (tag) => typeof tag === "string" && tag.toLowerCase() === "svg";
  function renderSVG(element, renderState, _styleProp, projection) {
    renderHTML(element, renderState, void 0, projection);
    for (const key in renderState.attrs) {
      element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]);
    }
  }
  function scrapeMotionValuesFromProps(props, prevProps, visualElement) {
    const newValues = scrapeMotionValuesFromProps$1(props, prevProps, visualElement);
    for (const key in props) {
      if (isMotionValue(props[key]) || isMotionValue(prevProps[key])) {
        const targetKey = transformPropOrder.indexOf(key) !== -1 ? "attr" + key.charAt(0).toUpperCase() + key.substring(1) : key;
        newValues[targetKey] = props[key];
      }
    }
    return newValues;
  }
  class SVGVisualElement extends DOMVisualElement {
    constructor() {
      super(...arguments);
      this.type = "svg";
      this.isSVGTag = false;
      this.measureInstanceViewportBox = createBox;
    }
    getBaseTargetFromProps(props, key) {
      return props[key];
    }
    readValueFromInstance(instance, key) {
      if (transformProps.has(key)) {
        const defaultType = getDefaultValueType(key);
        return defaultType ? defaultType.default || 0 : 0;
      }
      key = !camelCaseAttributes.has(key) ? camelToDash(key) : key;
      return instance.getAttribute(key);
    }
    scrapeMotionValuesFromProps(props, prevProps, visualElement) {
      return scrapeMotionValuesFromProps(props, prevProps, visualElement);
    }
    build(renderState, latestValues, props) {
      buildSVGAttrs(renderState, latestValues, this.isSVGTag, props.transformTemplate, props.style);
    }
    renderInstance(instance, renderState, styleProp, projection) {
      renderSVG(instance, renderState, styleProp, projection);
    }
    mount(instance) {
      this.isSVGTag = isSVGTag(instance.tagName);
      super.mount(instance);
    }
  }
  const numVariantProps = variantProps.length;
  function getVariantContext(visualElement) {
    if (!visualElement)
      return void 0;
    if (!visualElement.isControllingVariants) {
      const context2 = visualElement.parent ? getVariantContext(visualElement.parent) || {} : {};
      if (visualElement.props.initial !== void 0) {
        context2.initial = visualElement.props.initial;
      }
      return context2;
    }
    const context = {};
    for (let i = 0; i < numVariantProps; i++) {
      const name2 = variantProps[i];
      const prop = visualElement.props[name2];
      if (isVariantLabel(prop) || prop === false) {
        context[name2] = prop;
      }
    }
    return context;
  }
  function shallowCompare(next, prev) {
    if (!Array.isArray(prev))
      return false;
    const prevLength = prev.length;
    if (prevLength !== next.length)
      return false;
    for (let i = 0; i < prevLength; i++) {
      if (prev[i] !== next[i])
        return false;
    }
    return true;
  }
  const reversePriorityOrder = [...variantPriorityOrder].reverse();
  const numAnimationTypes = variantPriorityOrder.length;
  function createAnimateFunction(visualElement) {
    return (animations2) => {
      return Promise.all(animations2.map(({ animation, options }) => animateVisualElement(visualElement, animation, options)));
    };
  }
  function createAnimationState(visualElement) {
    let animate = createAnimateFunction(visualElement);
    let state = createState();
    let isInitialRender = true;
    let wasReset = false;
    const buildResolvedTypeValues = (type) => (acc, definition) => {
      var _a2;
      const resolved = resolveVariant(visualElement, definition, type === "exit" ? (_a2 = visualElement.presenceContext) == null ? void 0 : _a2.custom : void 0);
      if (resolved) {
        const { transition, transitionEnd, ...target2 } = resolved;
        acc = { ...acc, ...target2, ...transitionEnd };
      }
      return acc;
    };
    function setAnimateFunction(makeAnimator) {
      animate = makeAnimator(visualElement);
    }
    function animateChanges(changedActiveType) {
      const { props } = visualElement;
      const context = getVariantContext(visualElement.parent) || {};
      const animations2 = [];
      const removedKeys = /* @__PURE__ */ new Set();
      let encounteredKeys = {};
      let removedVariantIndex = Infinity;
      for (let i = 0; i < numAnimationTypes; i++) {
        const type = reversePriorityOrder[i];
        const typeState = state[type];
        const prop = props[type] !== void 0 ? props[type] : context[type];
        const propIsVariant = isVariantLabel(prop);
        const activeDelta = type === changedActiveType ? typeState.isActive : null;
        if (activeDelta === false)
          removedVariantIndex = i;
        let isInherited = prop === context[type] && prop !== props[type] && propIsVariant;
        if (isInherited && (isInitialRender || wasReset) && visualElement.manuallyAnimateOnMount) {
          isInherited = false;
        }
        typeState.protectedKeys = { ...encounteredKeys };
        if (
          // If it isn't active and hasn't *just* been set as inactive
          !typeState.isActive && activeDelta === null || // If we didn't and don't have any defined prop for this animation type
          !prop && !typeState.prevProp || // Or if the prop doesn't define an animation
          isAnimationControls(prop) || typeof prop === "boolean"
        ) {
          continue;
        }
        if (type === "exit" && typeState.isActive && activeDelta !== true) {
          if (typeState.prevResolvedValues) {
            encounteredKeys = {
              ...encounteredKeys,
              ...typeState.prevResolvedValues
            };
          }
          continue;
        }
        const variantDidChange = checkVariantsDidChange(typeState.prevProp, prop);
        let shouldAnimateType = variantDidChange || // If we're making this variant active, we want to always make it active
        type === changedActiveType && typeState.isActive && !isInherited && propIsVariant || // If we removed a higher-priority variant (i is in reverse order)
        i > removedVariantIndex && propIsVariant;
        let handledRemovedValues = false;
        const definitionList = Array.isArray(prop) ? prop : [prop];
        let resolvedValues = definitionList.reduce(buildResolvedTypeValues(type), {});
        if (activeDelta === false)
          resolvedValues = {};
        const { prevResolvedValues = {} } = typeState;
        const allKeys = {
          ...prevResolvedValues,
          ...resolvedValues
        };
        const markToAnimate = (key) => {
          shouldAnimateType = true;
          if (removedKeys.has(key)) {
            handledRemovedValues = true;
            removedKeys.delete(key);
          }
          typeState.needsAnimating[key] = true;
          const motionValue2 = visualElement.getValue(key);
          if (motionValue2)
            motionValue2.liveStyle = false;
        };
        for (const key in allKeys) {
          const next = resolvedValues[key];
          const prev = prevResolvedValues[key];
          if (encounteredKeys.hasOwnProperty(key))
            continue;
          let valueHasChanged = false;
          if (isKeyframesTarget(next) && isKeyframesTarget(prev)) {
            valueHasChanged = !shallowCompare(next, prev);
          } else {
            valueHasChanged = next !== prev;
          }
          if (valueHasChanged) {
            if (next !== void 0 && next !== null) {
              markToAnimate(key);
            } else {
              removedKeys.add(key);
            }
          } else if (next !== void 0 && removedKeys.has(key)) {
            markToAnimate(key);
          } else {
            typeState.protectedKeys[key] = true;
          }
        }
        typeState.prevProp = prop;
        typeState.prevResolvedValues = resolvedValues;
        if (typeState.isActive) {
          encounteredKeys = { ...encounteredKeys, ...resolvedValues };
        }
        if ((isInitialRender || wasReset) && visualElement.blockInitialAnimation) {
          shouldAnimateType = false;
        }
        const willAnimateViaParent = isInherited && variantDidChange;
        const needsAnimating = !willAnimateViaParent || handledRemovedValues;
        if (shouldAnimateType && needsAnimating) {
          animations2.push(...definitionList.map((animation) => {
            const options = { type };
            if (typeof animation === "string" && (isInitialRender || wasReset) && !willAnimateViaParent && visualElement.manuallyAnimateOnMount && visualElement.parent) {
              const { parent } = visualElement;
              const parentVariant = resolveVariant(parent, animation);
              if (parent.enteringChildren && parentVariant) {
                const { delayChildren } = parentVariant.transition || {};
                options.delay = calcChildStagger(parent.enteringChildren, visualElement, delayChildren);
              }
            }
            return {
              animation,
              options
            };
          }));
        }
      }
      if (removedKeys.size) {
        const fallbackAnimation = {};
        if (typeof props.initial !== "boolean") {
          const initialTransition = resolveVariant(visualElement, Array.isArray(props.initial) ? props.initial[0] : props.initial);
          if (initialTransition && initialTransition.transition) {
            fallbackAnimation.transition = initialTransition.transition;
          }
        }
        removedKeys.forEach((key) => {
          const fallbackTarget = visualElement.getBaseTarget(key);
          const motionValue2 = visualElement.getValue(key);
          if (motionValue2)
            motionValue2.liveStyle = true;
          fallbackAnimation[key] = fallbackTarget ?? null;
        });
        animations2.push({ animation: fallbackAnimation });
      }
      let shouldAnimate = Boolean(animations2.length);
      if (isInitialRender && (props.initial === false || props.initial === props.animate) && !visualElement.manuallyAnimateOnMount) {
        shouldAnimate = false;
      }
      isInitialRender = false;
      wasReset = false;
      return shouldAnimate ? animate(animations2) : Promise.resolve();
    }
    function setActive(type, isActive) {
      var _a2;
      if (state[type].isActive === isActive)
        return Promise.resolve();
      (_a2 = visualElement.variantChildren) == null ? void 0 : _a2.forEach((child) => {
        var _a3;
        return (_a3 = child.animationState) == null ? void 0 : _a3.setActive(type, isActive);
      });
      state[type].isActive = isActive;
      const animations2 = animateChanges(type);
      for (const key in state) {
        state[key].protectedKeys = {};
      }
      return animations2;
    }
    return {
      animateChanges,
      setActive,
      setAnimateFunction,
      getState: () => state,
      reset: () => {
        state = createState();
        wasReset = true;
      }
    };
  }
  function checkVariantsDidChange(prev, next) {
    if (typeof next === "string") {
      return next !== prev;
    } else if (Array.isArray(next)) {
      return !shallowCompare(next, prev);
    }
    return false;
  }
  function createTypeState(isActive = false) {
    return {
      isActive,
      protectedKeys: {},
      needsAnimating: {},
      prevResolvedValues: {}
    };
  }
  function createState() {
    return {
      animate: createTypeState(true),
      whileInView: createTypeState(),
      whileHover: createTypeState(),
      whileTap: createTypeState(),
      whileDrag: createTypeState(),
      whileFocus: createTypeState(),
      exit: createTypeState()
    };
  }
  function copyAxisInto(axis, originAxis) {
    axis.min = originAxis.min;
    axis.max = originAxis.max;
  }
  function copyBoxInto(box, originBox) {
    copyAxisInto(box.x, originBox.x);
    copyAxisInto(box.y, originBox.y);
  }
  function copyAxisDeltaInto(delta, originDelta) {
    delta.translate = originDelta.translate;
    delta.scale = originDelta.scale;
    delta.originPoint = originDelta.originPoint;
    delta.origin = originDelta.origin;
  }
  const SCALE_PRECISION = 1e-4;
  const SCALE_MIN = 1 - SCALE_PRECISION;
  const SCALE_MAX = 1 + SCALE_PRECISION;
  const TRANSLATE_PRECISION = 0.01;
  const TRANSLATE_MIN = 0 - TRANSLATE_PRECISION;
  const TRANSLATE_MAX = 0 + TRANSLATE_PRECISION;
  function calcLength(axis) {
    return axis.max - axis.min;
  }
  function isNear(value, target2, maxDistance) {
    return Math.abs(value - target2) <= maxDistance;
  }
  function calcAxisDelta(delta, source, target2, origin = 0.5) {
    delta.origin = origin;
    delta.originPoint = mixNumber$1(source.min, source.max, delta.origin);
    delta.scale = calcLength(target2) / calcLength(source);
    delta.translate = mixNumber$1(target2.min, target2.max, delta.origin) - delta.originPoint;
    if (delta.scale >= SCALE_MIN && delta.scale <= SCALE_MAX || isNaN(delta.scale)) {
      delta.scale = 1;
    }
    if (delta.translate >= TRANSLATE_MIN && delta.translate <= TRANSLATE_MAX || isNaN(delta.translate)) {
      delta.translate = 0;
    }
  }
  function calcBoxDelta(delta, source, target2, origin) {
    calcAxisDelta(delta.x, source.x, target2.x, origin ? origin.originX : void 0);
    calcAxisDelta(delta.y, source.y, target2.y, origin ? origin.originY : void 0);
  }
  function calcRelativeAxis(target2, relative, parent, anchor = 0) {
    const anchorPoint = anchor ? mixNumber$1(parent.min, parent.max, anchor) : parent.min;
    target2.min = anchorPoint + relative.min;
    target2.max = target2.min + calcLength(relative);
  }
  function calcRelativeBox(target2, relative, parent, anchor) {
    calcRelativeAxis(target2.x, relative.x, parent.x, anchor == null ? void 0 : anchor.x);
    calcRelativeAxis(target2.y, relative.y, parent.y, anchor == null ? void 0 : anchor.y);
  }
  function calcRelativeAxisPosition(target2, layout2, parent, anchor = 0) {
    const anchorPoint = anchor ? mixNumber$1(parent.min, parent.max, anchor) : parent.min;
    target2.min = layout2.min - anchorPoint;
    target2.max = target2.min + calcLength(layout2);
  }
  function calcRelativePosition(target2, layout2, parent, anchor) {
    calcRelativeAxisPosition(target2.x, layout2.x, parent.x, anchor == null ? void 0 : anchor.x);
    calcRelativeAxisPosition(target2.y, layout2.y, parent.y, anchor == null ? void 0 : anchor.y);
  }
  function removePointDelta(point, translate, scale2, originPoint, boxScale) {
    point -= translate;
    point = scalePoint(point, 1 / scale2, originPoint);
    if (boxScale !== void 0) {
      point = scalePoint(point, 1 / boxScale, originPoint);
    }
    return point;
  }
  function removeAxisDelta(axis, translate = 0, scale2 = 1, origin = 0.5, boxScale, originAxis = axis, sourceAxis = axis) {
    if (percent.test(translate)) {
      translate = parseFloat(translate);
      const relativeProgress = mixNumber$1(sourceAxis.min, sourceAxis.max, translate / 100);
      translate = relativeProgress - sourceAxis.min;
    }
    if (typeof translate !== "number")
      return;
    let originPoint = mixNumber$1(originAxis.min, originAxis.max, origin);
    if (axis === originAxis)
      originPoint -= translate;
    axis.min = removePointDelta(axis.min, translate, scale2, originPoint, boxScale);
    axis.max = removePointDelta(axis.max, translate, scale2, originPoint, boxScale);
  }
  function removeAxisTransforms(axis, transforms, [key, scaleKey, originKey], origin, sourceAxis) {
    removeAxisDelta(axis, transforms[key], transforms[scaleKey], transforms[originKey], transforms.scale, origin, sourceAxis);
  }
  const xKeys = ["x", "scaleX", "originX"];
  const yKeys = ["y", "scaleY", "originY"];
  function removeBoxTransforms(box, transforms, originBox, sourceBox) {
    removeAxisTransforms(box.x, transforms, xKeys, originBox ? originBox.x : void 0, sourceBox ? sourceBox.x : void 0);
    removeAxisTransforms(box.y, transforms, yKeys, originBox ? originBox.y : void 0, sourceBox ? sourceBox.y : void 0);
  }
  function isAxisDeltaZero(delta) {
    return delta.translate === 0 && delta.scale === 1;
  }
  function isDeltaZero(delta) {
    return isAxisDeltaZero(delta.x) && isAxisDeltaZero(delta.y);
  }
  function axisEquals(a, b) {
    return a.min === b.min && a.max === b.max;
  }
  function boxEquals(a, b) {
    return axisEquals(a.x, b.x) && axisEquals(a.y, b.y);
  }
  function axisEqualsRounded(a, b) {
    return Math.round(a.min) === Math.round(b.min) && Math.round(a.max) === Math.round(b.max);
  }
  function boxEqualsRounded(a, b) {
    return axisEqualsRounded(a.x, b.x) && axisEqualsRounded(a.y, b.y);
  }
  function aspectRatio(box) {
    return calcLength(box.x) / calcLength(box.y);
  }
  function axisDeltaEquals(a, b) {
    return a.translate === b.translate && a.scale === b.scale && a.originPoint === b.originPoint;
  }
  function eachAxis(callback) {
    return [callback("x"), callback("y")];
  }
  function buildProjectionTransform(delta, treeScale, latestTransform) {
    let transform2 = "";
    const xTranslate = delta.x.translate / treeScale.x;
    const yTranslate = delta.y.translate / treeScale.y;
    const zTranslate = (latestTransform == null ? void 0 : latestTransform.z) || 0;
    if (xTranslate || yTranslate || zTranslate) {
      transform2 = `translate3d(${xTranslate}px, ${yTranslate}px, ${zTranslate}px) `;
    }
    if (treeScale.x !== 1 || treeScale.y !== 1) {
      transform2 += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `;
    }
    if (latestTransform) {
      const { transformPerspective, rotate: rotate2, rotateX, rotateY, skewX, skewY } = latestTransform;
      if (transformPerspective)
        transform2 = `perspective(${transformPerspective}px) ${transform2}`;
      if (rotate2)
        transform2 += `rotate(${rotate2}deg) `;
      if (rotateX)
        transform2 += `rotateX(${rotateX}deg) `;
      if (rotateY)
        transform2 += `rotateY(${rotateY}deg) `;
      if (skewX)
        transform2 += `skewX(${skewX}deg) `;
      if (skewY)
        transform2 += `skewY(${skewY}deg) `;
    }
    const elementScaleX = delta.x.scale * treeScale.x;
    const elementScaleY = delta.y.scale * treeScale.y;
    if (elementScaleX !== 1 || elementScaleY !== 1) {
      transform2 += `scale(${elementScaleX}, ${elementScaleY})`;
    }
    return transform2 || "none";
  }
  const borderLabels = [
    "borderTopLeftRadius",
    "borderTopRightRadius",
    "borderBottomLeftRadius",
    "borderBottomRightRadius"
  ];
  const numBorders = borderLabels.length;
  const asNumber = (value) => typeof value === "string" ? parseFloat(value) : value;
  const isPx = (value) => typeof value === "number" || px.test(value);
  function mixValues(target2, follow, lead, progress2, shouldCrossfadeOpacity, isOnlyMember) {
    if (shouldCrossfadeOpacity) {
      target2.opacity = mixNumber$1(0, lead.opacity ?? 1, easeCrossfadeIn(progress2));
      target2.opacityExit = mixNumber$1(follow.opacity ?? 1, 0, easeCrossfadeOut(progress2));
    } else if (isOnlyMember) {
      target2.opacity = mixNumber$1(follow.opacity ?? 1, lead.opacity ?? 1, progress2);
    }
    for (let i = 0; i < numBorders; i++) {
      const borderLabel = borderLabels[i];
      let followRadius = getRadius(follow, borderLabel);
      let leadRadius = getRadius(lead, borderLabel);
      if (followRadius === void 0 && leadRadius === void 0)
        continue;
      followRadius || (followRadius = 0);
      leadRadius || (leadRadius = 0);
      const canMix = followRadius === 0 || leadRadius === 0 || isPx(followRadius) === isPx(leadRadius);
      if (canMix) {
        target2[borderLabel] = Math.max(mixNumber$1(asNumber(followRadius), asNumber(leadRadius), progress2), 0);
        if (percent.test(leadRadius) || percent.test(followRadius)) {
          target2[borderLabel] += "%";
        }
      } else {
        target2[borderLabel] = leadRadius;
      }
    }
    if (follow.rotate || lead.rotate) {
      target2.rotate = mixNumber$1(follow.rotate || 0, lead.rotate || 0, progress2);
    }
  }
  function getRadius(values, radiusName) {
    return values[radiusName] !== void 0 ? values[radiusName] : values.borderRadius;
  }
  const easeCrossfadeIn = /* @__PURE__ */ compress(0, 0.5, circOut);
  const easeCrossfadeOut = /* @__PURE__ */ compress(0.5, 0.95, noop);
  function compress(min, max, easing) {
    return (p) => {
      if (p < min)
        return 0;
      if (p > max)
        return 1;
      return easing(/* @__PURE__ */ progress$1(min, max, p));
    };
  }
  function animateSingleValue(value, keyframes2, options) {
    const motionValue$1 = isMotionValue(value) ? value : motionValue(value);
    motionValue$1.start(animateMotionValue("", motionValue$1, keyframes2, options));
    return motionValue$1.animation;
  }
  function addDomEvent(target2, eventName, handler, options = { passive: true }) {
    target2.addEventListener(eventName, handler, options);
    return () => target2.removeEventListener(eventName, handler);
  }
  const compareByDepth = (a, b) => a.depth - b.depth;
  class FlatTree {
    constructor() {
      this.children = [];
      this.isDirty = false;
    }
    add(child) {
      addUniqueItem(this.children, child);
      this.isDirty = true;
    }
    remove(child) {
      removeItem(this.children, child);
      this.isDirty = true;
    }
    forEach(callback) {
      this.isDirty && this.children.sort(compareByDepth);
      this.isDirty = false;
      this.children.forEach(callback);
    }
  }
  function delay(callback, timeout) {
    const start = time.now();
    const checkElapsed = ({ timestamp }) => {
      const elapsed = timestamp - start;
      if (elapsed >= timeout) {
        cancelFrame(checkElapsed);
        callback(elapsed - timeout);
      }
    };
    frame.setup(checkElapsed, true);
    return () => cancelFrame(checkElapsed);
  }
  function resolveMotionValue(value) {
    return isMotionValue(value) ? value.get() : value;
  }
  class NodeStack {
    constructor() {
      this.members = [];
    }
    add(node) {
      addUniqueItem(this.members, node);
      for (let i = this.members.length - 1; i >= 0; i--) {
        const member = this.members[i];
        if (member === node || member === this.lead || member === this.prevLead)
          continue;
        const inst = member.instance;
        if ((!inst || inst.isConnected === false) && !member.snapshot) {
          removeItem(this.members, member);
          member.unmount();
        }
      }
      node.scheduleRender();
    }
    remove(node) {
      removeItem(this.members, node);
      if (node === this.prevLead)
        this.prevLead = void 0;
      if (node === this.lead) {
        const prevLead = this.members[this.members.length - 1];
        if (prevLead)
          this.promote(prevLead);
      }
    }
    relegate(node) {
      var _a2;
      for (let i = this.members.indexOf(node) - 1; i >= 0; i--) {
        const member = this.members[i];
        if (member.isPresent !== false && ((_a2 = member.instance) == null ? void 0 : _a2.isConnected) !== false) {
          this.promote(member);
          return true;
        }
      }
      return false;
    }
    promote(node, preserveFollowOpacity) {
      var _a2;
      const prevLead = this.lead;
      if (node === prevLead)
        return;
      this.prevLead = prevLead;
      this.lead = node;
      node.show();
      if (prevLead) {
        prevLead.updateSnapshot();
        node.scheduleRender();
        const { layoutDependency: prevDep } = prevLead.options;
        const { layoutDependency: nextDep } = node.options;
        if (prevDep === void 0 || prevDep !== nextDep) {
          node.resumeFrom = prevLead;
          if (preserveFollowOpacity)
            prevLead.preserveOpacity = true;
          if (prevLead.snapshot) {
            node.snapshot = prevLead.snapshot;
            node.snapshot.latestValues = prevLead.animationValues || prevLead.latestValues;
          }
          if ((_a2 = node.root) == null ? void 0 : _a2.isUpdating)
            node.isLayoutDirty = true;
        }
        if (node.options.crossfade === false)
          prevLead.hide();
      }
    }
    exitAnimationComplete() {
      this.members.forEach((member) => {
        var _a2, _b, _c, _d, _e;
        (_b = (_a2 = member.options).onExitComplete) == null ? void 0 : _b.call(_a2);
        (_e = (_c = member.resumingFrom) == null ? void 0 : (_d = _c.options).onExitComplete) == null ? void 0 : _e.call(_d);
      });
    }
    scheduleRender() {
      this.members.forEach((member) => member.instance && member.scheduleRender(false));
    }
    removeLeadSnapshot() {
      var _a2;
      if ((_a2 = this.lead) == null ? void 0 : _a2.snapshot)
        this.lead.snapshot = void 0;
    }
  }
  const globalProjectionState = {
    /**
     * Global flag as to whether the tree has animated since the last time
     * we resized the window
     */
    hasAnimatedSinceResize: true,
    /**
     * We set this to true once, on the first update. Any nodes added to the tree beyond that
     * update will be given a `data-projection-id` attribute.
     */
    hasEverUpdated: false
  };
  const transformAxes = ["", "X", "Y", "Z"];
  const animationTarget = 1e3;
  let id$1 = 0;
  function resetDistortingTransform(key, visualElement, values, sharedAnimationValues) {
    const { latestValues } = visualElement;
    if (latestValues[key]) {
      values[key] = latestValues[key];
      visualElement.setStaticValue(key, 0);
      if (sharedAnimationValues) {
        sharedAnimationValues[key] = 0;
      }
    }
  }
  function cancelTreeOptimisedTransformAnimations(projectionNode) {
    projectionNode.hasCheckedOptimisedAppear = true;
    if (projectionNode.root === projectionNode)
      return;
    const { visualElement } = projectionNode.options;
    if (!visualElement)
      return;
    const appearId = getOptimisedAppearId(visualElement);
    if (window.MotionHasOptimisedAnimation(appearId, "transform")) {
      const { layout: layout2, layoutId } = projectionNode.options;
      window.MotionCancelOptimisedAnimation(appearId, "transform", frame, !(layout2 || layoutId));
    }
    const { parent } = projectionNode;
    if (parent && !parent.hasCheckedOptimisedAppear) {
      cancelTreeOptimisedTransformAnimations(parent);
    }
  }
  function createProjectionNode$1({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform }) {
    return class ProjectionNode {
      constructor(latestValues = {}, parent = defaultParent == null ? void 0 : defaultParent()) {
        this.id = id$1++;
        this.animationId = 0;
        this.animationCommitId = 0;
        this.children = /* @__PURE__ */ new Set();
        this.options = {};
        this.isTreeAnimating = false;
        this.isAnimationBlocked = false;
        this.isLayoutDirty = false;
        this.isProjectionDirty = false;
        this.isSharedProjectionDirty = false;
        this.isTransformDirty = false;
        this.updateManuallyBlocked = false;
        this.updateBlockedByResize = false;
        this.isUpdating = false;
        this.isSVG = false;
        this.needsReset = false;
        this.shouldResetTransform = false;
        this.hasCheckedOptimisedAppear = false;
        this.treeScale = { x: 1, y: 1 };
        this.eventHandlers = /* @__PURE__ */ new Map();
        this.hasTreeAnimated = false;
        this.layoutVersion = 0;
        this.updateScheduled = false;
        this.scheduleUpdate = () => this.update();
        this.projectionUpdateScheduled = false;
        this.checkUpdateFailed = () => {
          if (this.isUpdating) {
            this.isUpdating = false;
            this.clearAllSnapshots();
          }
        };
        this.updateProjection = () => {
          this.projectionUpdateScheduled = false;
          this.nodes.forEach(propagateDirtyNodes);
          this.nodes.forEach(resolveTargetDelta);
          this.nodes.forEach(calcProjection);
          this.nodes.forEach(cleanDirtyNodes);
        };
        this.resolvedRelativeTargetAt = 0;
        this.linkedParentVersion = 0;
        this.hasProjected = false;
        this.isVisible = true;
        this.animationProgress = 0;
        this.sharedNodes = /* @__PURE__ */ new Map();
        this.latestValues = latestValues;
        this.root = parent ? parent.root || parent : this;
        this.path = parent ? [...parent.path, parent] : [];
        this.parent = parent;
        this.depth = parent ? parent.depth + 1 : 0;
        for (let i = 0; i < this.path.length; i++) {
          this.path[i].shouldResetTransform = true;
        }
        if (this.root === this)
          this.nodes = new FlatTree();
      }
      addEventListener(name2, handler) {
        if (!this.eventHandlers.has(name2)) {
          this.eventHandlers.set(name2, new SubscriptionManager());
        }
        return this.eventHandlers.get(name2).add(handler);
      }
      notifyListeners(name2, ...args) {
        const subscriptionManager = this.eventHandlers.get(name2);
        subscriptionManager && subscriptionManager.notify(...args);
      }
      hasListeners(name2) {
        return this.eventHandlers.has(name2);
      }
      /**
       * Lifecycles
       */
      mount(instance) {
        if (this.instance)
          return;
        this.isSVG = isSVGElement(instance) && !isSVGSVGElement(instance);
        this.instance = instance;
        const { layoutId, layout: layout2, visualElement } = this.options;
        if (visualElement && !visualElement.current) {
          visualElement.mount(instance);
        }
        this.root.nodes.add(this);
        this.parent && this.parent.children.add(this);
        if (this.root.hasTreeAnimated && (layout2 || layoutId)) {
          this.isLayoutDirty = true;
        }
        if (attachResizeListener) {
          let cancelDelay;
          let innerWidth = 0;
          const resizeUnblockUpdate = () => this.root.updateBlockedByResize = false;
          frame.read(() => {
            innerWidth = window.innerWidth;
          });
          attachResizeListener(instance, () => {
            const newInnerWidth = window.innerWidth;
            if (newInnerWidth === innerWidth)
              return;
            innerWidth = newInnerWidth;
            this.root.updateBlockedByResize = true;
            cancelDelay && cancelDelay();
            cancelDelay = delay(resizeUnblockUpdate, 250);
            if (globalProjectionState.hasAnimatedSinceResize) {
              globalProjectionState.hasAnimatedSinceResize = false;
              this.nodes.forEach(finishAnimation);
            }
          });
        }
        if (layoutId) {
          this.root.registerSharedNode(layoutId, this);
        }
        if (this.options.animate !== false && visualElement && (layoutId || layout2)) {
          this.addEventListener("didUpdate", ({ delta, hasLayoutChanged, hasRelativeLayoutChanged, layout: newLayout }) => {
            if (this.isTreeAnimationBlocked()) {
              this.target = void 0;
              this.relativeTarget = void 0;
              return;
            }
            const layoutTransition = this.options.transition || visualElement.getDefaultTransition() || defaultLayoutTransition;
            const { onLayoutAnimationStart, onLayoutAnimationComplete } = visualElement.getProps();
            const hasTargetChanged = !this.targetLayout || !boxEqualsRounded(this.targetLayout, newLayout);
            const hasOnlyRelativeTargetChanged = !hasLayoutChanged && hasRelativeLayoutChanged;
            if (this.options.layoutRoot || this.resumeFrom || hasOnlyRelativeTargetChanged || hasLayoutChanged && (hasTargetChanged || !this.currentAnimation)) {
              if (this.resumeFrom) {
                this.resumingFrom = this.resumeFrom;
                this.resumingFrom.resumingFrom = void 0;
              }
              const animationOptions = {
                ...getValueTransition(layoutTransition, "layout"),
                onPlay: onLayoutAnimationStart,
                onComplete: onLayoutAnimationComplete
              };
              if (visualElement.shouldReduceMotion || this.options.layoutRoot) {
                animationOptions.delay = 0;
                animationOptions.type = false;
              }
              this.startAnimation(animationOptions);
              this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged);
            } else {
              if (!hasLayoutChanged) {
                finishAnimation(this);
              }
              if (this.isLead() && this.options.onExitComplete) {
                this.options.onExitComplete();
              }
            }
            this.targetLayout = newLayout;
          });
        }
      }
      unmount() {
        this.options.layoutId && this.willUpdate();
        this.root.nodes.remove(this);
        const stack = this.getStack();
        stack && stack.remove(this);
        this.parent && this.parent.children.delete(this);
        this.instance = void 0;
        this.eventHandlers.clear();
        cancelFrame(this.updateProjection);
      }
      // only on the root
      blockUpdate() {
        this.updateManuallyBlocked = true;
      }
      unblockUpdate() {
        this.updateManuallyBlocked = false;
      }
      isUpdateBlocked() {
        return this.updateManuallyBlocked || this.updateBlockedByResize;
      }
      isTreeAnimationBlocked() {
        return this.isAnimationBlocked || this.parent && this.parent.isTreeAnimationBlocked() || false;
      }
      // Note: currently only running on root node
      startUpdate() {
        if (this.isUpdateBlocked())
          return;
        this.isUpdating = true;
        this.nodes && this.nodes.forEach(resetSkewAndRotation);
        this.animationId++;
      }
      getTransformTemplate() {
        const { visualElement } = this.options;
        return visualElement && visualElement.getProps().transformTemplate;
      }
      willUpdate(shouldNotifyListeners = true) {
        this.root.hasTreeAnimated = true;
        if (this.root.isUpdateBlocked()) {
          this.options.onExitComplete && this.options.onExitComplete();
          return;
        }
        if (window.MotionCancelOptimisedAnimation && !this.hasCheckedOptimisedAppear) {
          cancelTreeOptimisedTransformAnimations(this);
        }
        !this.root.isUpdating && this.root.startUpdate();
        if (this.isLayoutDirty)
          return;
        this.isLayoutDirty = true;
        for (let i = 0; i < this.path.length; i++) {
          const node = this.path[i];
          node.shouldResetTransform = true;
          if (typeof node.latestValues.x === "string" || typeof node.latestValues.y === "string") {
            node.isLayoutDirty = true;
          }
          node.updateScroll("snapshot");
          if (node.options.layoutRoot) {
            node.willUpdate(false);
          }
        }
        const { layoutId, layout: layout2 } = this.options;
        if (layoutId === void 0 && !layout2)
          return;
        const transformTemplate = this.getTransformTemplate();
        this.prevTransformTemplateValue = transformTemplate ? transformTemplate(this.latestValues, "") : void 0;
        this.updateSnapshot();
        shouldNotifyListeners && this.notifyListeners("willUpdate");
      }
      update() {
        this.updateScheduled = false;
        const updateWasBlocked = this.isUpdateBlocked();
        if (updateWasBlocked) {
          const wasBlockedByResize = this.updateBlockedByResize;
          this.unblockUpdate();
          this.updateBlockedByResize = false;
          this.clearAllSnapshots();
          if (wasBlockedByResize) {
            this.nodes.forEach(forceLayoutMeasure);
          }
          this.nodes.forEach(clearMeasurements);
          return;
        }
        if (this.animationId <= this.animationCommitId) {
          this.nodes.forEach(clearIsLayoutDirty);
          return;
        }
        this.animationCommitId = this.animationId;
        if (!this.isUpdating) {
          this.nodes.forEach(clearIsLayoutDirty);
        } else {
          this.isUpdating = false;
          this.nodes.forEach(ensureDraggedNodesSnapshotted);
          this.nodes.forEach(resetTransformStyle);
          this.nodes.forEach(updateLayout);
          this.nodes.forEach(notifyLayoutUpdate);
        }
        this.clearAllSnapshots();
        const now2 = time.now();
        frameData.delta = clamp(0, 1e3 / 60, now2 - frameData.timestamp);
        frameData.timestamp = now2;
        frameData.isProcessing = true;
        frameSteps.update.process(frameData);
        frameSteps.preRender.process(frameData);
        frameSteps.render.process(frameData);
        frameData.isProcessing = false;
      }
      didUpdate() {
        if (!this.updateScheduled) {
          this.updateScheduled = true;
          microtask.read(this.scheduleUpdate);
        }
      }
      clearAllSnapshots() {
        this.nodes.forEach(clearSnapshot);
        this.sharedNodes.forEach(removeLeadSnapshots);
      }
      scheduleUpdateProjection() {
        if (!this.projectionUpdateScheduled) {
          this.projectionUpdateScheduled = true;
          frame.preRender(this.updateProjection, false, true);
        }
      }
      scheduleCheckAfterUnmount() {
        frame.postRender(() => {
          if (this.isLayoutDirty) {
            this.root.didUpdate();
          } else {
            this.root.checkUpdateFailed();
          }
        });
      }
      /**
       * Update measurements
       */
      updateSnapshot() {
        if (this.snapshot || !this.instance)
          return;
        this.snapshot = this.measure();
        if (this.snapshot && !calcLength(this.snapshot.measuredBox.x) && !calcLength(this.snapshot.measuredBox.y)) {
          this.snapshot = void 0;
        }
      }
      updateLayout() {
        if (!this.instance)
          return;
        this.updateScroll();
        if (!(this.options.alwaysMeasureLayout && this.isLead()) && !this.isLayoutDirty) {
          return;
        }
        if (this.resumeFrom && !this.resumeFrom.instance) {
          for (let i = 0; i < this.path.length; i++) {
            const node = this.path[i];
            node.updateScroll();
          }
        }
        const prevLayout = this.layout;
        this.layout = this.measure(false);
        this.layoutVersion++;
        if (!this.layoutCorrected)
          this.layoutCorrected = createBox();
        this.isLayoutDirty = false;
        this.projectionDelta = void 0;
        this.notifyListeners("measure", this.layout.layoutBox);
        const { visualElement } = this.options;
        visualElement && visualElement.notify("LayoutMeasure", this.layout.layoutBox, prevLayout ? prevLayout.layoutBox : void 0);
      }
      updateScroll(phase = "measure") {
        let needsMeasurement = Boolean(this.options.layoutScroll && this.instance);
        if (this.scroll && this.scroll.animationId === this.root.animationId && this.scroll.phase === phase) {
          needsMeasurement = false;
        }
        if (needsMeasurement && this.instance) {
          const isRoot = checkIsScrollRoot(this.instance);
          this.scroll = {
            animationId: this.root.animationId,
            phase,
            isRoot,
            offset: measureScroll(this.instance),
            wasRoot: this.scroll ? this.scroll.isRoot : isRoot
          };
        }
      }
      resetTransform() {
        if (!resetTransform)
          return;
        const isResetRequested = this.isLayoutDirty || this.shouldResetTransform || this.options.alwaysMeasureLayout;
        const hasProjection = this.projectionDelta && !isDeltaZero(this.projectionDelta);
        const transformTemplate = this.getTransformTemplate();
        const transformTemplateValue = transformTemplate ? transformTemplate(this.latestValues, "") : void 0;
        const transformTemplateHasChanged = transformTemplateValue !== this.prevTransformTemplateValue;
        if (isResetRequested && this.instance && (hasProjection || hasTransform(this.latestValues) || transformTemplateHasChanged)) {
          resetTransform(this.instance, transformTemplateValue);
          this.shouldResetTransform = false;
          this.scheduleRender();
        }
      }
      measure(removeTransform = true) {
        const pageBox = this.measurePageBox();
        let layoutBox = this.removeElementScroll(pageBox);
        if (removeTransform) {
          layoutBox = this.removeTransform(layoutBox);
        }
        roundBox(layoutBox);
        return {
          animationId: this.root.animationId,
          measuredBox: pageBox,
          layoutBox,
          latestValues: {},
          source: this.id
        };
      }
      measurePageBox() {
        var _a2;
        const { visualElement } = this.options;
        if (!visualElement)
          return createBox();
        const box = visualElement.measureViewportBox();
        const wasInScrollRoot = ((_a2 = this.scroll) == null ? void 0 : _a2.wasRoot) || this.path.some(checkNodeWasScrollRoot);
        if (!wasInScrollRoot) {
          const { scroll } = this.root;
          if (scroll) {
            translateAxis(box.x, scroll.offset.x);
            translateAxis(box.y, scroll.offset.y);
          }
        }
        return box;
      }
      removeElementScroll(box) {
        var _a2;
        const boxWithoutScroll = createBox();
        copyBoxInto(boxWithoutScroll, box);
        if ((_a2 = this.scroll) == null ? void 0 : _a2.wasRoot) {
          return boxWithoutScroll;
        }
        for (let i = 0; i < this.path.length; i++) {
          const node = this.path[i];
          const { scroll, options } = node;
          if (node !== this.root && scroll && options.layoutScroll) {
            if (scroll.wasRoot) {
              copyBoxInto(boxWithoutScroll, box);
            }
            translateAxis(boxWithoutScroll.x, scroll.offset.x);
            translateAxis(boxWithoutScroll.y, scroll.offset.y);
          }
        }
        return boxWithoutScroll;
      }
      applyTransform(box, transformOnly = false, output) {
        var _a2, _b;
        const withTransforms = output || createBox();
        copyBoxInto(withTransforms, box);
        for (let i = 0; i < this.path.length; i++) {
          const node = this.path[i];
          if (!transformOnly && node.options.layoutScroll && node.scroll && node !== node.root) {
            translateAxis(withTransforms.x, -node.scroll.offset.x);
            translateAxis(withTransforms.y, -node.scroll.offset.y);
          }
          if (!hasTransform(node.latestValues))
            continue;
          transformBox(withTransforms, node.latestValues, (_a2 = node.layout) == null ? void 0 : _a2.layoutBox);
        }
        if (hasTransform(this.latestValues)) {
          transformBox(withTransforms, this.latestValues, (_b = this.layout) == null ? void 0 : _b.layoutBox);
        }
        return withTransforms;
      }
      removeTransform(box) {
        var _a2;
        const boxWithoutTransform = createBox();
        copyBoxInto(boxWithoutTransform, box);
        for (let i = 0; i < this.path.length; i++) {
          const node = this.path[i];
          if (!hasTransform(node.latestValues))
            continue;
          let sourceBox;
          if (node.instance) {
            hasScale(node.latestValues) && node.updateSnapshot();
            sourceBox = createBox();
            copyBoxInto(sourceBox, node.measurePageBox());
          }
          removeBoxTransforms(boxWithoutTransform, node.latestValues, (_a2 = node.snapshot) == null ? void 0 : _a2.layoutBox, sourceBox);
        }
        if (hasTransform(this.latestValues)) {
          removeBoxTransforms(boxWithoutTransform, this.latestValues);
        }
        return boxWithoutTransform;
      }
      setTargetDelta(delta) {
        this.targetDelta = delta;
        this.root.scheduleUpdateProjection();
        this.isProjectionDirty = true;
      }
      setOptions(options) {
        this.options = {
          ...this.options,
          ...options,
          crossfade: options.crossfade !== void 0 ? options.crossfade : true
        };
      }
      clearMeasurements() {
        this.scroll = void 0;
        this.layout = void 0;
        this.snapshot = void 0;
        this.prevTransformTemplateValue = void 0;
        this.targetDelta = void 0;
        this.target = void 0;
        this.isLayoutDirty = false;
      }
      forceRelativeParentToResolveTarget() {
        if (!this.relativeParent)
          return;
        if (this.relativeParent.resolvedRelativeTargetAt !== frameData.timestamp) {
          this.relativeParent.resolveTargetDelta(true);
        }
      }
      resolveTargetDelta(forceRecalculation = false) {
        var _a2;
        const lead = this.getLead();
        this.isProjectionDirty || (this.isProjectionDirty = lead.isProjectionDirty);
        this.isTransformDirty || (this.isTransformDirty = lead.isTransformDirty);
        this.isSharedProjectionDirty || (this.isSharedProjectionDirty = lead.isSharedProjectionDirty);
        const isShared = Boolean(this.resumingFrom) || this !== lead;
        const canSkip = !(forceRecalculation || isShared && this.isSharedProjectionDirty || this.isProjectionDirty || ((_a2 = this.parent) == null ? void 0 : _a2.isProjectionDirty) || this.attemptToResolveRelativeTarget || this.root.updateBlockedByResize);
        if (canSkip)
          return;
        const { layout: layout2, layoutId } = this.options;
        if (!this.layout || !(layout2 || layoutId))
          return;
        this.resolvedRelativeTargetAt = frameData.timestamp;
        const relativeParent = this.getClosestProjectingParent();
        if (relativeParent && this.linkedParentVersion !== relativeParent.layoutVersion && !relativeParent.options.layoutRoot) {
          this.removeRelativeTarget();
        }
        if (!this.targetDelta && !this.relativeTarget) {
          if (this.options.layoutAnchor !== false && relativeParent && relativeParent.layout) {
            this.createRelativeTarget(relativeParent, this.layout.layoutBox, relativeParent.layout.layoutBox);
          } else {
            this.removeRelativeTarget();
          }
        }
        if (!this.relativeTarget && !this.targetDelta)
          return;
        if (!this.target) {
          this.target = createBox();
          this.targetWithTransforms = createBox();
        }
        if (this.relativeTarget && this.relativeTargetOrigin && this.relativeParent && this.relativeParent.target) {
          this.forceRelativeParentToResolveTarget();
          calcRelativeBox(this.target, this.relativeTarget, this.relativeParent.target, this.options.layoutAnchor || void 0);
        } else if (this.targetDelta) {
          if (Boolean(this.resumingFrom)) {
            this.applyTransform(this.layout.layoutBox, false, this.target);
          } else {
            copyBoxInto(this.target, this.layout.layoutBox);
          }
          applyBoxDelta(this.target, this.targetDelta);
        } else {
          copyBoxInto(this.target, this.layout.layoutBox);
        }
        if (this.attemptToResolveRelativeTarget) {
          this.attemptToResolveRelativeTarget = false;
          if (this.options.layoutAnchor !== false && relativeParent && Boolean(relativeParent.resumingFrom) === Boolean(this.resumingFrom) && !relativeParent.options.layoutScroll && relativeParent.target && this.animationProgress !== 1) {
            this.createRelativeTarget(relativeParent, this.target, relativeParent.target);
          } else {
            this.relativeParent = this.relativeTarget = void 0;
          }
        }
      }
      getClosestProjectingParent() {
        if (!this.parent || hasScale(this.parent.latestValues) || has2DTranslate(this.parent.latestValues)) {
          return void 0;
        }
        if (this.parent.isProjecting()) {
          return this.parent;
        } else {
          return this.parent.getClosestProjectingParent();
        }
      }
      isProjecting() {
        return Boolean((this.relativeTarget || this.targetDelta || this.options.layoutRoot) && this.layout);
      }
      createRelativeTarget(relativeParent, layout2, parentLayout) {
        this.relativeParent = relativeParent;
        this.linkedParentVersion = relativeParent.layoutVersion;
        this.forceRelativeParentToResolveTarget();
        this.relativeTarget = createBox();
        this.relativeTargetOrigin = createBox();
        calcRelativePosition(this.relativeTargetOrigin, layout2, parentLayout, this.options.layoutAnchor || void 0);
        copyBoxInto(this.relativeTarget, this.relativeTargetOrigin);
      }
      removeRelativeTarget() {
        this.relativeParent = this.relativeTarget = void 0;
      }
      calcProjection() {
        var _a2;
        const lead = this.getLead();
        const isShared = Boolean(this.resumingFrom) || this !== lead;
        let canSkip = true;
        if (this.isProjectionDirty || ((_a2 = this.parent) == null ? void 0 : _a2.isProjectionDirty)) {
          canSkip = false;
        }
        if (isShared && (this.isSharedProjectionDirty || this.isTransformDirty)) {
          canSkip = false;
        }
        if (this.resolvedRelativeTargetAt === frameData.timestamp) {
          canSkip = false;
        }
        if (canSkip)
          return;
        const { layout: layout2, layoutId } = this.options;
        this.isTreeAnimating = Boolean(this.parent && this.parent.isTreeAnimating || this.currentAnimation || this.pendingAnimation);
        if (!this.isTreeAnimating) {
          this.targetDelta = this.relativeTarget = void 0;
        }
        if (!this.layout || !(layout2 || layoutId))
          return;
        copyBoxInto(this.layoutCorrected, this.layout.layoutBox);
        const prevTreeScaleX = this.treeScale.x;
        const prevTreeScaleY = this.treeScale.y;
        applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared);
        if (lead.layout && !lead.target && (this.treeScale.x !== 1 || this.treeScale.y !== 1)) {
          lead.target = lead.layout.layoutBox;
          lead.targetWithTransforms = createBox();
        }
        const { target: target2 } = lead;
        if (!target2) {
          if (this.prevProjectionDelta) {
            this.createProjectionDeltas();
            this.scheduleRender();
          }
          return;
        }
        if (!this.projectionDelta || !this.prevProjectionDelta) {
          this.createProjectionDeltas();
        } else {
          copyAxisDeltaInto(this.prevProjectionDelta.x, this.projectionDelta.x);
          copyAxisDeltaInto(this.prevProjectionDelta.y, this.projectionDelta.y);
        }
        calcBoxDelta(this.projectionDelta, this.layoutCorrected, target2, this.latestValues);
        if (this.treeScale.x !== prevTreeScaleX || this.treeScale.y !== prevTreeScaleY || !axisDeltaEquals(this.projectionDelta.x, this.prevProjectionDelta.x) || !axisDeltaEquals(this.projectionDelta.y, this.prevProjectionDelta.y)) {
          this.hasProjected = true;
          this.scheduleRender();
          this.notifyListeners("projectionUpdate", target2);
        }
      }
      hide() {
        this.isVisible = false;
      }
      show() {
        this.isVisible = true;
      }
      scheduleRender(notifyAll2 = true) {
        var _a2;
        (_a2 = this.options.visualElement) == null ? void 0 : _a2.scheduleRender();
        if (notifyAll2) {
          const stack = this.getStack();
          stack && stack.scheduleRender();
        }
        if (this.resumingFrom && !this.resumingFrom.instance) {
          this.resumingFrom = void 0;
        }
      }
      createProjectionDeltas() {
        this.prevProjectionDelta = createDelta();
        this.projectionDelta = createDelta();
        this.projectionDeltaWithTransform = createDelta();
      }
      setAnimationOrigin(delta, hasOnlyRelativeTargetChanged = false) {
        const snapshot = this.snapshot;
        const snapshotLatestValues = snapshot ? snapshot.latestValues : {};
        const mixedValues = { ...this.latestValues };
        const targetDelta = createDelta();
        if (!this.relativeParent || !this.relativeParent.options.layoutRoot) {
          this.relativeTarget = this.relativeTargetOrigin = void 0;
        }
        this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged;
        const relativeLayout = createBox();
        const snapshotSource = snapshot ? snapshot.source : void 0;
        const layoutSource = this.layout ? this.layout.source : void 0;
        const isSharedLayoutAnimation = snapshotSource !== layoutSource;
        const stack = this.getStack();
        const isOnlyMember = !stack || stack.members.length <= 1;
        const shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation && !isOnlyMember && this.options.crossfade === true && !this.path.some(hasOpacityCrossfade));
        this.animationProgress = 0;
        let prevRelativeTarget;
        this.mixTargetDelta = (latest) => {
          const progress2 = latest / 1e3;
          mixAxisDelta(targetDelta.x, delta.x, progress2);
          mixAxisDelta(targetDelta.y, delta.y, progress2);
          this.setTargetDelta(targetDelta);
          if (this.relativeTarget && this.relativeTargetOrigin && this.layout && this.relativeParent && this.relativeParent.layout) {
            calcRelativePosition(relativeLayout, this.layout.layoutBox, this.relativeParent.layout.layoutBox, this.options.layoutAnchor || void 0);
            mixBox(this.relativeTarget, this.relativeTargetOrigin, relativeLayout, progress2);
            if (prevRelativeTarget && boxEquals(this.relativeTarget, prevRelativeTarget)) {
              this.isProjectionDirty = false;
            }
            if (!prevRelativeTarget)
              prevRelativeTarget = createBox();
            copyBoxInto(prevRelativeTarget, this.relativeTarget);
          }
          if (isSharedLayoutAnimation) {
            this.animationValues = mixedValues;
            mixValues(mixedValues, snapshotLatestValues, this.latestValues, progress2, shouldCrossfadeOpacity, isOnlyMember);
          }
          this.root.scheduleUpdateProjection();
          this.scheduleRender();
          this.animationProgress = progress2;
        };
        this.mixTargetDelta(this.options.layoutRoot ? 1e3 : 0);
      }
      startAnimation(options) {
        var _a2, _b, _c;
        this.notifyListeners("animationStart");
        (_a2 = this.currentAnimation) == null ? void 0 : _a2.stop();
        (_c = (_b = this.resumingFrom) == null ? void 0 : _b.currentAnimation) == null ? void 0 : _c.stop();
        if (this.pendingAnimation) {
          cancelFrame(this.pendingAnimation);
          this.pendingAnimation = void 0;
        }
        this.pendingAnimation = frame.update(() => {
          globalProjectionState.hasAnimatedSinceResize = true;
          this.motionValue || (this.motionValue = motionValue(0));
          this.motionValue.jump(0, false);
          this.currentAnimation = animateSingleValue(this.motionValue, [0, 1e3], {
            ...options,
            velocity: 0,
            isSync: true,
            onUpdate: (latest) => {
              this.mixTargetDelta(latest);
              options.onUpdate && options.onUpdate(latest);
            },
            onStop: () => {
            },
            onComplete: () => {
              options.onComplete && options.onComplete();
              this.completeAnimation();
            }
          });
          if (this.resumingFrom) {
            this.resumingFrom.currentAnimation = this.currentAnimation;
          }
          this.pendingAnimation = void 0;
        });
      }
      completeAnimation() {
        if (this.resumingFrom) {
          this.resumingFrom.currentAnimation = void 0;
          this.resumingFrom.preserveOpacity = void 0;
        }
        const stack = this.getStack();
        stack && stack.exitAnimationComplete();
        this.resumingFrom = this.currentAnimation = this.animationValues = void 0;
        this.notifyListeners("animationComplete");
      }
      finishAnimation() {
        if (this.currentAnimation) {
          this.mixTargetDelta && this.mixTargetDelta(animationTarget);
          this.currentAnimation.stop();
        }
        this.completeAnimation();
      }
      applyTransformsToTarget() {
        const lead = this.getLead();
        let { targetWithTransforms, target: target2, layout: layout2, latestValues } = lead;
        if (!targetWithTransforms || !target2 || !layout2)
          return;
        if (this !== lead && this.layout && layout2 && shouldAnimatePositionOnly(this.options.animationType, this.layout.layoutBox, layout2.layoutBox)) {
          target2 = this.target || createBox();
          const xLength = calcLength(this.layout.layoutBox.x);
          target2.x.min = lead.target.x.min;
          target2.x.max = target2.x.min + xLength;
          const yLength = calcLength(this.layout.layoutBox.y);
          target2.y.min = lead.target.y.min;
          target2.y.max = target2.y.min + yLength;
        }
        copyBoxInto(targetWithTransforms, target2);
        transformBox(targetWithTransforms, latestValues);
        calcBoxDelta(this.projectionDeltaWithTransform, this.layoutCorrected, targetWithTransforms, latestValues);
      }
      registerSharedNode(layoutId, node) {
        if (!this.sharedNodes.has(layoutId)) {
          this.sharedNodes.set(layoutId, new NodeStack());
        }
        const stack = this.sharedNodes.get(layoutId);
        stack.add(node);
        const config = node.options.initialPromotionConfig;
        node.promote({
          transition: config ? config.transition : void 0,
          preserveFollowOpacity: config && config.shouldPreserveFollowOpacity ? config.shouldPreserveFollowOpacity(node) : void 0
        });
      }
      isLead() {
        const stack = this.getStack();
        return stack ? stack.lead === this : true;
      }
      getLead() {
        var _a2;
        const { layoutId } = this.options;
        return layoutId ? ((_a2 = this.getStack()) == null ? void 0 : _a2.lead) || this : this;
      }
      getPrevLead() {
        var _a2;
        const { layoutId } = this.options;
        return layoutId ? (_a2 = this.getStack()) == null ? void 0 : _a2.prevLead : void 0;
      }
      getStack() {
        const { layoutId } = this.options;
        if (layoutId)
          return this.root.sharedNodes.get(layoutId);
      }
      promote({ needsReset, transition, preserveFollowOpacity } = {}) {
        const stack = this.getStack();
        if (stack)
          stack.promote(this, preserveFollowOpacity);
        if (needsReset) {
          this.projectionDelta = void 0;
          this.needsReset = true;
        }
        if (transition)
          this.setOptions({ transition });
      }
      relegate() {
        const stack = this.getStack();
        if (stack) {
          return stack.relegate(this);
        } else {
          return false;
        }
      }
      resetSkewAndRotation() {
        const { visualElement } = this.options;
        if (!visualElement)
          return;
        let hasDistortingTransform = false;
        const { latestValues } = visualElement;
        if (latestValues.z || latestValues.rotate || latestValues.rotateX || latestValues.rotateY || latestValues.rotateZ || latestValues.skewX || latestValues.skewY) {
          hasDistortingTransform = true;
        }
        if (!hasDistortingTransform)
          return;
        const resetValues = {};
        if (latestValues.z) {
          resetDistortingTransform("z", visualElement, resetValues, this.animationValues);
        }
        for (let i = 0; i < transformAxes.length; i++) {
          resetDistortingTransform(`rotate${transformAxes[i]}`, visualElement, resetValues, this.animationValues);
          resetDistortingTransform(`skew${transformAxes[i]}`, visualElement, resetValues, this.animationValues);
        }
        visualElement.render();
        for (const key in resetValues) {
          visualElement.setStaticValue(key, resetValues[key]);
          if (this.animationValues) {
            this.animationValues[key] = resetValues[key];
          }
        }
        visualElement.scheduleRender();
      }
      applyProjectionStyles(targetStyle, styleProp) {
        if (!this.instance || this.isSVG)
          return;
        if (!this.isVisible) {
          targetStyle.visibility = "hidden";
          return;
        }
        const transformTemplate = this.getTransformTemplate();
        if (this.needsReset) {
          this.needsReset = false;
          targetStyle.visibility = "";
          targetStyle.opacity = "";
          targetStyle.pointerEvents = resolveMotionValue(styleProp == null ? void 0 : styleProp.pointerEvents) || "";
          targetStyle.transform = transformTemplate ? transformTemplate(this.latestValues, "") : "none";
          return;
        }
        const lead = this.getLead();
        if (!this.projectionDelta || !this.layout || !lead.target) {
          if (this.options.layoutId) {
            targetStyle.opacity = this.latestValues.opacity !== void 0 ? this.latestValues.opacity : 1;
            targetStyle.pointerEvents = resolveMotionValue(styleProp == null ? void 0 : styleProp.pointerEvents) || "";
          }
          if (this.hasProjected && !hasTransform(this.latestValues)) {
            targetStyle.transform = transformTemplate ? transformTemplate({}, "") : "none";
            this.hasProjected = false;
          }
          return;
        }
        targetStyle.visibility = "";
        const valuesToRender = lead.animationValues || lead.latestValues;
        this.applyTransformsToTarget();
        let transform2 = buildProjectionTransform(this.projectionDeltaWithTransform, this.treeScale, valuesToRender);
        if (transformTemplate) {
          transform2 = transformTemplate(valuesToRender, transform2);
        }
        targetStyle.transform = transform2;
        const { x, y } = this.projectionDelta;
        targetStyle.transformOrigin = `${x.origin * 100}% ${y.origin * 100}% 0`;
        if (lead.animationValues) {
          targetStyle.opacity = lead === this ? valuesToRender.opacity ?? this.latestValues.opacity ?? 1 : this.preserveOpacity ? this.latestValues.opacity : valuesToRender.opacityExit;
        } else {
          targetStyle.opacity = lead === this ? valuesToRender.opacity !== void 0 ? valuesToRender.opacity : "" : valuesToRender.opacityExit !== void 0 ? valuesToRender.opacityExit : 0;
        }
        for (const key in scaleCorrectors) {
          if (valuesToRender[key] === void 0)
            continue;
          const { correct, applyTo, isCSSVariable } = scaleCorrectors[key];
          const corrected = transform2 === "none" ? valuesToRender[key] : correct(valuesToRender[key], lead);
          if (applyTo) {
            const num = applyTo.length;
            for (let i = 0; i < num; i++) {
              targetStyle[applyTo[i]] = corrected;
            }
          } else {
            if (isCSSVariable) {
              this.options.visualElement.renderState.vars[key] = corrected;
            } else {
              targetStyle[key] = corrected;
            }
          }
        }
        if (this.options.layoutId) {
          targetStyle.pointerEvents = lead === this ? resolveMotionValue(styleProp == null ? void 0 : styleProp.pointerEvents) || "" : "none";
        }
      }
      clearSnapshot() {
        this.resumeFrom = this.snapshot = void 0;
      }
      // Only run on root
      resetTree() {
        this.root.nodes.forEach((node) => {
          var _a2;
          return (_a2 = node.currentAnimation) == null ? void 0 : _a2.stop();
        });
        this.root.nodes.forEach(clearMeasurements);
        this.root.sharedNodes.clear();
      }
    };
  }
  function updateLayout(node) {
    node.updateLayout();
  }
  function notifyLayoutUpdate(node) {
    var _a2;
    const snapshot = ((_a2 = node.resumeFrom) == null ? void 0 : _a2.snapshot) || node.snapshot;
    if (node.isLead() && node.layout && snapshot && node.hasListeners("didUpdate")) {
      const { layoutBox: layout2, measuredBox: measuredLayout } = node.layout;
      const { animationType } = node.options;
      const isShared = snapshot.source !== node.layout.source;
      if (animationType === "size") {
        eachAxis((axis) => {
          const axisSnapshot = isShared ? snapshot.measuredBox[axis] : snapshot.layoutBox[axis];
          const length = calcLength(axisSnapshot);
          axisSnapshot.min = layout2[axis].min;
          axisSnapshot.max = axisSnapshot.min + length;
        });
      } else if (animationType === "x" || animationType === "y") {
        const snapAxis = animationType === "x" ? "y" : "x";
        copyAxisInto(isShared ? snapshot.measuredBox[snapAxis] : snapshot.layoutBox[snapAxis], layout2[snapAxis]);
      } else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout2)) {
        eachAxis((axis) => {
          const axisSnapshot = isShared ? snapshot.measuredBox[axis] : snapshot.layoutBox[axis];
          const length = calcLength(layout2[axis]);
          axisSnapshot.max = axisSnapshot.min + length;
          if (node.relativeTarget && !node.currentAnimation) {
            node.isProjectionDirty = true;
            node.relativeTarget[axis].max = node.relativeTarget[axis].min + length;
          }
        });
      }
      const layoutDelta = createDelta();
      calcBoxDelta(layoutDelta, layout2, snapshot.layoutBox);
      const visualDelta = createDelta();
      if (isShared) {
        calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measuredBox);
      } else {
        calcBoxDelta(visualDelta, layout2, snapshot.layoutBox);
      }
      const hasLayoutChanged = !isDeltaZero(layoutDelta);
      let hasRelativeLayoutChanged = false;
      if (!node.resumeFrom) {
        const relativeParent = node.getClosestProjectingParent();
        if (relativeParent && !relativeParent.resumeFrom) {
          const { snapshot: parentSnapshot, layout: parentLayout } = relativeParent;
          if (parentSnapshot && parentLayout) {
            const anchor = node.options.layoutAnchor || void 0;
            const relativeSnapshot = createBox();
            calcRelativePosition(relativeSnapshot, snapshot.layoutBox, parentSnapshot.layoutBox, anchor);
            const relativeLayout = createBox();
            calcRelativePosition(relativeLayout, layout2, parentLayout.layoutBox, anchor);
            if (!boxEqualsRounded(relativeSnapshot, relativeLayout)) {
              hasRelativeLayoutChanged = true;
            }
            if (relativeParent.options.layoutRoot) {
              node.relativeTarget = relativeLayout;
              node.relativeTargetOrigin = relativeSnapshot;
              node.relativeParent = relativeParent;
            }
          }
        }
      }
      node.notifyListeners("didUpdate", {
        layout: layout2,
        snapshot,
        delta: visualDelta,
        layoutDelta,
        hasLayoutChanged,
        hasRelativeLayoutChanged
      });
    } else if (node.isLead()) {
      const { onExitComplete } = node.options;
      onExitComplete && onExitComplete();
    }
    node.options.transition = void 0;
  }
  function propagateDirtyNodes(node) {
    if (!node.parent)
      return;
    if (!node.isProjecting()) {
      node.isProjectionDirty = node.parent.isProjectionDirty;
    }
    node.isSharedProjectionDirty || (node.isSharedProjectionDirty = Boolean(node.isProjectionDirty || node.parent.isProjectionDirty || node.parent.isSharedProjectionDirty));
    node.isTransformDirty || (node.isTransformDirty = node.parent.isTransformDirty);
  }
  function cleanDirtyNodes(node) {
    node.isProjectionDirty = node.isSharedProjectionDirty = node.isTransformDirty = false;
  }
  function clearSnapshot(node) {
    node.clearSnapshot();
  }
  function clearMeasurements(node) {
    node.clearMeasurements();
  }
  function forceLayoutMeasure(node) {
    node.isLayoutDirty = true;
    node.updateLayout();
  }
  function clearIsLayoutDirty(node) {
    node.isLayoutDirty = false;
  }
  function ensureDraggedNodesSnapshotted(node) {
    if (node.isAnimationBlocked && node.layout && !node.isLayoutDirty) {
      node.snapshot = node.layout;
      node.isLayoutDirty = true;
    }
  }
  function resetTransformStyle(node) {
    const { visualElement } = node.options;
    if (visualElement && visualElement.getProps().onBeforeLayoutMeasure) {
      visualElement.notify("BeforeLayoutMeasure");
    }
    node.resetTransform();
  }
  function finishAnimation(node) {
    node.finishAnimation();
    node.targetDelta = node.relativeTarget = node.target = void 0;
    node.isProjectionDirty = true;
  }
  function resolveTargetDelta(node) {
    node.resolveTargetDelta();
  }
  function calcProjection(node) {
    node.calcProjection();
  }
  function resetSkewAndRotation(node) {
    node.resetSkewAndRotation();
  }
  function removeLeadSnapshots(stack) {
    stack.removeLeadSnapshot();
  }
  function mixAxisDelta(output, delta, p) {
    output.translate = mixNumber$1(delta.translate, 0, p);
    output.scale = mixNumber$1(delta.scale, 1, p);
    output.origin = delta.origin;
    output.originPoint = delta.originPoint;
  }
  function mixAxis(output, from, to, p) {
    output.min = mixNumber$1(from.min, to.min, p);
    output.max = mixNumber$1(from.max, to.max, p);
  }
  function mixBox(output, from, to, p) {
    mixAxis(output.x, from.x, to.x, p);
    mixAxis(output.y, from.y, to.y, p);
  }
  function hasOpacityCrossfade(node) {
    return node.animationValues && node.animationValues.opacityExit !== void 0;
  }
  const defaultLayoutTransition = {
    duration: 0.45,
    ease: [0.4, 0, 0.1, 1]
  };
  const userAgentContains = (string) => typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().includes(string);
  const roundPoint = userAgentContains("applewebkit/") && !userAgentContains("chrome/") ? Math.round : noop;
  function roundAxis(axis) {
    axis.min = roundPoint(axis.min);
    axis.max = roundPoint(axis.max);
  }
  function roundBox(box) {
    roundAxis(box.x);
    roundAxis(box.y);
  }
  function shouldAnimatePositionOnly(animationType, snapshot, layout2) {
    return animationType === "position" || animationType === "preserve-aspect" && !isNear(aspectRatio(snapshot), aspectRatio(layout2), 0.2);
  }
  function checkNodeWasScrollRoot(node) {
    var _a2;
    return node !== node.root && ((_a2 = node.scroll) == null ? void 0 : _a2.wasRoot);
  }
  const DocumentProjectionNode = createProjectionNode$1({
    attachResizeListener: (ref, notify) => addDomEvent(ref, "resize", notify),
    measureScroll: () => {
      var _a2, _b;
      return {
        x: document.documentElement.scrollLeft || ((_a2 = document.body) == null ? void 0 : _a2.scrollLeft) || 0,
        y: document.documentElement.scrollTop || ((_b = document.body) == null ? void 0 : _b.scrollTop) || 0
      };
    },
    checkIsScrollRoot: () => true
  });
  const rootProjectionNode = {
    current: void 0
  };
  const HTMLProjectionNode = createProjectionNode$1({
    measureScroll: (instance) => ({
      x: instance.scrollLeft,
      y: instance.scrollTop
    }),
    defaultParent: () => {
      if (!rootProjectionNode.current) {
        const documentNode = new DocumentProjectionNode({});
        documentNode.mount(window);
        documentNode.setOptions({ layoutScroll: true });
        rootProjectionNode.current = documentNode;
      }
      return rootProjectionNode.current;
    },
    resetTransform: (instance, value) => {
      instance.style.transform = value !== void 0 ? value : "none";
    },
    checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed")
  });
  const MotionConfigContext = reactExports.createContext({
    transformPagePoint: (p) => p,
    isStatic: false,
    reducedMotion: "never"
  });
  function usePresence(subscribe = true) {
    const context = reactExports.useContext(PresenceContext);
    if (context === null)
      return [true, null];
    const { isPresent, onExitComplete, register } = context;
    const id2 = reactExports.useId();
    reactExports.useEffect(() => {
      if (subscribe) {
        return register(id2);
      }
    }, [subscribe]);
    const safeToRemove = reactExports.useCallback(() => subscribe && onExitComplete && onExitComplete(id2), [id2, onExitComplete, subscribe]);
    return !isPresent && onExitComplete ? [false, safeToRemove] : [true];
  }
  const LazyContext = reactExports.createContext({ strict: false });
  const featureProps = {
    animation: [
      "animate",
      "variants",
      "whileHover",
      "whileTap",
      "exit",
      "whileInView",
      "whileFocus",
      "whileDrag"
    ],
    exit: ["exit"],
    drag: ["drag", "dragControls"],
    focus: ["whileFocus"],
    hover: ["whileHover", "onHoverStart", "onHoverEnd"],
    tap: ["whileTap", "onTap", "onTapStart", "onTapCancel"],
    pan: ["onPan", "onPanStart", "onPanSessionStart", "onPanEnd"],
    inView: ["whileInView", "onViewportEnter", "onViewportLeave"],
    layout: ["layout", "layoutId"]
  };
  let isInitialized = false;
  function initFeatureDefinitions() {
    if (isInitialized)
      return;
    const initialFeatureDefinitions = {};
    for (const key in featureProps) {
      initialFeatureDefinitions[key] = {
        isEnabled: (props) => featureProps[key].some((name2) => !!props[name2])
      };
    }
    setFeatureDefinitions(initialFeatureDefinitions);
    isInitialized = true;
  }
  function getInitializedFeatureDefinitions() {
    initFeatureDefinitions();
    return getFeatureDefinitions();
  }
  function loadFeatures(features) {
    const featureDefinitions2 = getInitializedFeatureDefinitions();
    for (const key in features) {
      featureDefinitions2[key] = {
        ...featureDefinitions2[key],
        ...features[key]
      };
    }
    setFeatureDefinitions(featureDefinitions2);
  }
  const validMotionProps = /* @__PURE__ */ new Set([
    "animate",
    "exit",
    "variants",
    "initial",
    "style",
    "values",
    "variants",
    "transition",
    "transformTemplate",
    "custom",
    "inherit",
    "onBeforeLayoutMeasure",
    "onAnimationStart",
    "onAnimationComplete",
    "onUpdate",
    "onDragStart",
    "onDrag",
    "onDragEnd",
    "onMeasureDragConstraints",
    "onDirectionLock",
    "onDragTransitionEnd",
    "_dragX",
    "_dragY",
    "onHoverStart",
    "onHoverEnd",
    "onViewportEnter",
    "onViewportLeave",
    "globalTapTarget",
    "propagate",
    "ignoreStrict",
    "viewport"
  ]);
  function isValidMotionProp(key) {
    return key.startsWith("while") || key.startsWith("drag") && key !== "draggable" || key.startsWith("layout") || key.startsWith("onTap") || key.startsWith("onPan") || key.startsWith("onLayout") || validMotionProps.has(key);
  }
  let shouldForward = (key) => !isValidMotionProp(key);
  function loadExternalIsValidProp(isValidProp) {
    if (typeof isValidProp !== "function")
      return;
    shouldForward = (key) => key.startsWith("on") ? !isValidMotionProp(key) : isValidProp(key);
  }
  try {
    const emotionPkg = "@emotion/is-prop-valid";
    loadExternalIsValidProp(require(emotionPkg).default);
  } catch {
  }
  function filterProps(props, isDom, forwardMotionProps) {
    const filteredProps = {};
    for (const key in props) {
      if (key === "values" && typeof props.values === "object")
        continue;
      if (isMotionValue(props[key]))
        continue;
      if (shouldForward(key) || forwardMotionProps === true && isValidMotionProp(key) || !isDom && !isValidMotionProp(key) || // If trying to use native HTML drag events, forward drag listeners
      props["draggable"] && key.startsWith("onDrag")) {
        filteredProps[key] = props[key];
      }
    }
    return filteredProps;
  }
  const MotionContext = /* @__PURE__ */ reactExports.createContext({});
  function getCurrentTreeVariants(props, context) {
    if (isControllingVariants(props)) {
      const { initial, animate } = props;
      return {
        initial: initial === false || isVariantLabel(initial) ? initial : void 0,
        animate: isVariantLabel(animate) ? animate : void 0
      };
    }
    return props.inherit !== false ? context : {};
  }
  function useCreateMotionContext(props) {
    const { initial, animate } = getCurrentTreeVariants(props, reactExports.useContext(MotionContext));
    return reactExports.useMemo(() => ({ initial, animate }), [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate)]);
  }
  function variantLabelsAsDependency(prop) {
    return Array.isArray(prop) ? prop.join(" ") : prop;
  }
  const createHtmlRenderState = () => ({
    style: {},
    transform: {},
    transformOrigin: {},
    vars: {}
  });
  function copyRawValuesOnly(target2, source, props) {
    for (const key in source) {
      if (!isMotionValue(source[key]) && !isForcedMotionValue(key, props)) {
        target2[key] = source[key];
      }
    }
  }
  function useInitialMotionValues({ transformTemplate }, visualState) {
    return reactExports.useMemo(() => {
      const state = createHtmlRenderState();
      buildHTMLStyles(state, visualState, transformTemplate);
      return Object.assign({}, state.vars, state.style);
    }, [visualState]);
  }
  function useStyle(props, visualState) {
    const styleProp = props.style || {};
    const style = {};
    copyRawValuesOnly(style, styleProp, props);
    Object.assign(style, useInitialMotionValues(props, visualState));
    return style;
  }
  function useHTMLProps(props, visualState) {
    const htmlProps = {};
    const style = useStyle(props, visualState);
    if (props.drag && props.dragListener !== false) {
      htmlProps.draggable = false;
      style.userSelect = style.WebkitUserSelect = style.WebkitTouchCallout = "none";
      style.touchAction = props.drag === true ? "none" : `pan-${props.drag === "x" ? "y" : "x"}`;
    }
    if (props.tabIndex === void 0 && (props.onTap || props.onTapStart || props.whileTap)) {
      htmlProps.tabIndex = 0;
    }
    htmlProps.style = style;
    return htmlProps;
  }
  const createSvgRenderState = () => ({
    ...createHtmlRenderState(),
    attrs: {}
  });
  function useSVGProps(props, visualState, _isStatic, Component) {
    const visualProps = reactExports.useMemo(() => {
      const state = createSvgRenderState();
      buildSVGAttrs(state, visualState, isSVGTag(Component), props.transformTemplate, props.style);
      return {
        ...state.attrs,
        style: { ...state.style }
      };
    }, [visualState]);
    if (props.style) {
      const rawStyles = {};
      copyRawValuesOnly(rawStyles, props.style, props);
      visualProps.style = { ...rawStyles, ...visualProps.style };
    }
    return visualProps;
  }
  const lowercaseSVGElements = [
    "animate",
    "circle",
    "defs",
    "desc",
    "ellipse",
    "g",
    "image",
    "line",
    "filter",
    "marker",
    "mask",
    "metadata",
    "path",
    "pattern",
    "polygon",
    "polyline",
    "rect",
    "stop",
    "switch",
    "symbol",
    "svg",
    "text",
    "tspan",
    "use",
    "view"
  ];
  function isSVGComponent(Component) {
    if (
      /**
       * If it's not a string, it's a custom React component. Currently we only support
       * HTML custom React components.
       */
      typeof Component !== "string" || /**
       * If it contains a dash, the element is a custom HTML webcomponent.
       */
      Component.includes("-")
    ) {
      return false;
    } else if (
      /**
       * If it's in our list of lowercase SVG tags, it's an SVG component
       */
      lowercaseSVGElements.indexOf(Component) > -1 || /**
       * If it contains a capital letter, it's an SVG component
       */
      /[A-Z]/u.test(Component)
    ) {
      return true;
    }
    return false;
  }
  function useRender(Component, props, ref, { latestValues }, isStatic, forwardMotionProps = false, isSVG) {
    const useVisualProps = isSVG ?? isSVGComponent(Component) ? useSVGProps : useHTMLProps;
    const visualProps = useVisualProps(props, latestValues, isStatic, Component);
    const filteredProps = filterProps(props, typeof Component === "string", forwardMotionProps);
    const elementProps = Component !== reactExports.Fragment ? { ...filteredProps, ...visualProps, ref } : {};
    const { children } = props;
    const renderedChildren = reactExports.useMemo(() => isMotionValue(children) ? children.get() : children, [children]);
    return reactExports.createElement(Component, {
      ...elementProps,
      children: renderedChildren
    });
  }
  function makeState({ scrapeMotionValuesFromProps: scrapeMotionValuesFromProps2, createRenderState }, props, context, presenceContext) {
    const state = {
      latestValues: makeLatestValues(props, context, presenceContext, scrapeMotionValuesFromProps2),
      renderState: createRenderState()
    };
    return state;
  }
  function makeLatestValues(props, context, presenceContext, scrapeMotionValues) {
    const values = {};
    const motionValues = scrapeMotionValues(props, {});
    for (const key in motionValues) {
      values[key] = resolveMotionValue(motionValues[key]);
    }
    let { initial, animate } = props;
    const isControllingVariants$1 = isControllingVariants(props);
    const isVariantNode$1 = isVariantNode(props);
    if (context && isVariantNode$1 && !isControllingVariants$1 && props.inherit !== false) {
      if (initial === void 0)
        initial = context.initial;
      if (animate === void 0)
        animate = context.animate;
    }
    let isInitialAnimationBlocked = presenceContext ? presenceContext.initial === false : false;
    isInitialAnimationBlocked = isInitialAnimationBlocked || initial === false;
    const variantToSet = isInitialAnimationBlocked ? animate : initial;
    if (variantToSet && typeof variantToSet !== "boolean" && !isAnimationControls(variantToSet)) {
      const list2 = Array.isArray(variantToSet) ? variantToSet : [variantToSet];
      for (let i = 0; i < list2.length; i++) {
        const resolved = resolveVariantFromProps(props, list2[i]);
        if (resolved) {
          const { transitionEnd, transition, ...target2 } = resolved;
          for (const key in target2) {
            let valueTarget = target2[key];
            if (Array.isArray(valueTarget)) {
              const index = isInitialAnimationBlocked ? valueTarget.length - 1 : 0;
              valueTarget = valueTarget[index];
            }
            if (valueTarget !== null) {
              values[key] = valueTarget;
            }
          }
          for (const key in transitionEnd) {
            values[key] = transitionEnd[key];
          }
        }
      }
    }
    return values;
  }
  const makeUseVisualState = (config) => (props, isStatic) => {
    const context = reactExports.useContext(MotionContext);
    const presenceContext = reactExports.useContext(PresenceContext);
    const make = () => makeState(config, props, context, presenceContext);
    return isStatic ? make() : useConstant(make);
  };
  const useHTMLVisualState = /* @__PURE__ */ makeUseVisualState({
    scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1,
    createRenderState: createHtmlRenderState
  });
  const useSVGVisualState = /* @__PURE__ */ makeUseVisualState({
    scrapeMotionValuesFromProps,
    createRenderState: createSvgRenderState
  });
  const motionComponentSymbol = Symbol.for("motionComponentSymbol");
  function useMotionRef(visualState, visualElement, externalRef) {
    const externalRefContainer = reactExports.useRef(externalRef);
    reactExports.useInsertionEffect(() => {
      externalRefContainer.current = externalRef;
    });
    const refCleanup = reactExports.useRef(null);
    return reactExports.useCallback((instance) => {
      var _a2;
      if (instance) {
        (_a2 = visualState.onMount) == null ? void 0 : _a2.call(visualState, instance);
      }
      const ref = externalRefContainer.current;
      if (typeof ref === "function") {
        if (instance) {
          const cleanup = ref(instance);
          if (typeof cleanup === "function") {
            refCleanup.current = cleanup;
          }
        } else if (refCleanup.current) {
          refCleanup.current();
          refCleanup.current = null;
        } else {
          ref(instance);
        }
      } else if (ref) {
        ref.current = instance;
      }
      if (visualElement) {
        instance ? visualElement.mount(instance) : visualElement.unmount();
      }
    }, [visualElement]);
  }
  const SwitchLayoutGroupContext = reactExports.createContext({});
  function isRefObject(ref) {
    return ref && typeof ref === "object" && Object.prototype.hasOwnProperty.call(ref, "current");
  }
  function useVisualElement(Component, visualState, props, createVisualElement, ProjectionNodeConstructor, isSVG) {
    var _a2, _b;
    const { visualElement: parent } = reactExports.useContext(MotionContext);
    const lazyContext = reactExports.useContext(LazyContext);
    const presenceContext = reactExports.useContext(PresenceContext);
    const motionConfig = reactExports.useContext(MotionConfigContext);
    const reducedMotionConfig = motionConfig.reducedMotion;
    const skipAnimations = motionConfig.skipAnimations;
    const visualElementRef = reactExports.useRef(null);
    const hasMountedOnce = reactExports.useRef(false);
    createVisualElement = createVisualElement || lazyContext.renderer;
    if (!visualElementRef.current && createVisualElement) {
      visualElementRef.current = createVisualElement(Component, {
        visualState,
        parent,
        props,
        presenceContext,
        blockInitialAnimation: presenceContext ? presenceContext.initial === false : false,
        reducedMotionConfig,
        skipAnimations,
        isSVG
      });
      if (hasMountedOnce.current && visualElementRef.current) {
        visualElementRef.current.manuallyAnimateOnMount = true;
      }
    }
    const visualElement = visualElementRef.current;
    const initialLayoutGroupConfig = reactExports.useContext(SwitchLayoutGroupContext);
    if (visualElement && !visualElement.projection && ProjectionNodeConstructor && (visualElement.type === "html" || visualElement.type === "svg")) {
      createProjectionNode(visualElementRef.current, props, ProjectionNodeConstructor, initialLayoutGroupConfig);
    }
    const isMounted = reactExports.useRef(false);
    reactExports.useInsertionEffect(() => {
      if (visualElement && isMounted.current) {
        visualElement.update(props, presenceContext);
      }
    });
    const optimisedAppearId = props[optimizedAppearDataAttribute];
    const wantsHandoff = reactExports.useRef(Boolean(optimisedAppearId) && typeof window !== "undefined" && !((_a2 = window.MotionHandoffIsComplete) == null ? void 0 : _a2.call(window, optimisedAppearId)) && ((_b = window.MotionHasOptimisedAnimation) == null ? void 0 : _b.call(window, optimisedAppearId)));
    useIsomorphicLayoutEffect(() => {
      hasMountedOnce.current = true;
      if (!visualElement)
        return;
      isMounted.current = true;
      window.MotionIsMounted = true;
      visualElement.updateFeatures();
      visualElement.scheduleRenderMicrotask();
      if (wantsHandoff.current && visualElement.animationState) {
        visualElement.animationState.animateChanges();
      }
    });
    reactExports.useEffect(() => {
      if (!visualElement)
        return;
      if (!wantsHandoff.current && visualElement.animationState) {
        visualElement.animationState.animateChanges();
      }
      if (wantsHandoff.current) {
        queueMicrotask(() => {
          var _a3;
          (_a3 = window.MotionHandoffMarkAsComplete) == null ? void 0 : _a3.call(window, optimisedAppearId);
        });
        wantsHandoff.current = false;
      }
      visualElement.enteringChildren = void 0;
    });
    return visualElement;
  }
  function createProjectionNode(visualElement, props, ProjectionNodeConstructor, initialPromotionConfig) {
    const { layoutId, layout: layout2, drag: drag2, dragConstraints, layoutScroll, layoutRoot, layoutAnchor, layoutCrossfade } = props;
    visualElement.projection = new ProjectionNodeConstructor(visualElement.latestValues, props["data-framer-portal-id"] ? void 0 : getClosestProjectingNode(visualElement.parent));
    visualElement.projection.setOptions({
      layoutId,
      layout: layout2,
      alwaysMeasureLayout: Boolean(drag2) || dragConstraints && isRefObject(dragConstraints),
      visualElement,
      /**
       * TODO: Update options in an effect. This could be tricky as it'll be too late
       * to update by the time layout animations run.
       * We also need to fix this safeToRemove by linking it up to the one returned by usePresence,
       * ensuring it gets called if there's no potential layout animations.
       *
       */
      animationType: typeof layout2 === "string" ? layout2 : "both",
      initialPromotionConfig,
      crossfade: layoutCrossfade,
      layoutScroll,
      layoutRoot,
      layoutAnchor
    });
  }
  function getClosestProjectingNode(visualElement) {
    if (!visualElement)
      return void 0;
    return visualElement.options.allowProjection !== false ? visualElement.projection : getClosestProjectingNode(visualElement.parent);
  }
  function createMotionComponent(Component, { forwardMotionProps = false, type } = {}, preloadedFeatures, createVisualElement) {
    preloadedFeatures && loadFeatures(preloadedFeatures);
    const isSVG = type ? type === "svg" : isSVGComponent(Component);
    const useVisualState = isSVG ? useSVGVisualState : useHTMLVisualState;
    function MotionDOMComponent(props, externalRef) {
      let MeasureLayout2;
      const configAndProps = {
        ...reactExports.useContext(MotionConfigContext),
        ...props,
        layoutId: useLayoutId(props)
      };
      const { isStatic } = configAndProps;
      const context = useCreateMotionContext(props);
      const visualState = useVisualState(props, isStatic);
      if (!isStatic && typeof window !== "undefined") {
        useStrictMode();
        const layoutProjection = getProjectionFunctionality(configAndProps);
        MeasureLayout2 = layoutProjection.MeasureLayout;
        context.visualElement = useVisualElement(Component, visualState, configAndProps, createVisualElement, layoutProjection.ProjectionNode, isSVG);
      }
      return jsxRuntimeExports.jsxs(MotionContext.Provider, { value: context, children: [MeasureLayout2 && context.visualElement ? jsxRuntimeExports.jsx(MeasureLayout2, { visualElement: context.visualElement, ...configAndProps }) : null, useRender(Component, props, useMotionRef(visualState, context.visualElement, externalRef), visualState, isStatic, forwardMotionProps, isSVG)] });
    }
    MotionDOMComponent.displayName = `motion.${typeof Component === "string" ? Component : `create(${Component.displayName ?? Component.name ?? ""})`}`;
    const ForwardRefMotionComponent = reactExports.forwardRef(MotionDOMComponent);
    ForwardRefMotionComponent[motionComponentSymbol] = Component;
    return ForwardRefMotionComponent;
  }
  function useLayoutId({ layoutId }) {
    const layoutGroupId = reactExports.useContext(LayoutGroupContext).id;
    return layoutGroupId && layoutId !== void 0 ? layoutGroupId + "-" + layoutId : layoutId;
  }
  function useStrictMode(configAndProps, preloadedFeatures) {
    reactExports.useContext(LazyContext).strict;
  }
  function getProjectionFunctionality(props) {
    const featureDefinitions2 = getInitializedFeatureDefinitions();
    const { drag: drag2, layout: layout2 } = featureDefinitions2;
    if (!drag2 && !layout2)
      return {};
    const combined = { ...drag2, ...layout2 };
    return {
      MeasureLayout: (drag2 == null ? void 0 : drag2.isEnabled(props)) || (layout2 == null ? void 0 : layout2.isEnabled(props)) ? combined.MeasureLayout : void 0,
      ProjectionNode: combined.ProjectionNode
    };
  }
  function createMotionProxy(preloadedFeatures, createVisualElement) {
    if (typeof Proxy === "undefined") {
      return createMotionComponent;
    }
    const componentCache = /* @__PURE__ */ new Map();
    const factory = (Component, options) => {
      return createMotionComponent(Component, options, preloadedFeatures, createVisualElement);
    };
    const deprecatedFactoryFunction = (Component, options) => {
      return factory(Component, options);
    };
    return new Proxy(deprecatedFactoryFunction, {
      /**
       * Called when `motion` is referenced with a prop: `motion.div`, `motion.input` etc.
       * The prop name is passed through as `key` and we can use that to generate a `motion`
       * DOM component with that name.
       */
      get: (_target, key) => {
        if (key === "create")
          return factory;
        if (!componentCache.has(key)) {
          componentCache.set(key, createMotionComponent(key, void 0, preloadedFeatures, createVisualElement));
        }
        return componentCache.get(key);
      }
    });
  }
  const createDomVisualElement = (Component, options) => {
    const isSVG = options.isSVG ?? isSVGComponent(Component);
    return isSVG ? new SVGVisualElement(options) : new HTMLVisualElement(options, {
      allowProjection: Component !== reactExports.Fragment
    });
  };
  class AnimationFeature extends Feature {
    /**
     * We dynamically generate the AnimationState manager as it contains a reference
     * to the underlying animation library. We only want to load that if we load this,
     * so people can optionally code split it out using the `m` component.
     */
    constructor(node) {
      super(node);
      node.animationState || (node.animationState = createAnimationState(node));
    }
    updateAnimationControlsSubscription() {
      const { animate } = this.node.getProps();
      if (isAnimationControls(animate)) {
        this.unmountControls = animate.subscribe(this.node);
      }
    }
    /**
     * Subscribe any provided AnimationControls to the component's VisualElement
     */
    mount() {
      this.updateAnimationControlsSubscription();
    }
    update() {
      const { animate } = this.node.getProps();
      const { animate: prevAnimate } = this.node.prevProps || {};
      if (animate !== prevAnimate) {
        this.updateAnimationControlsSubscription();
      }
    }
    unmount() {
      var _a2;
      this.node.animationState.reset();
      (_a2 = this.unmountControls) == null ? void 0 : _a2.call(this);
    }
  }
  let id = 0;
  class ExitAnimationFeature extends Feature {
    constructor() {
      super(...arguments);
      this.id = id++;
      this.isExitComplete = false;
    }
    update() {
      var _a2;
      if (!this.node.presenceContext)
        return;
      const { isPresent, onExitComplete } = this.node.presenceContext;
      const { isPresent: prevIsPresent } = this.node.prevPresenceContext || {};
      if (!this.node.animationState || isPresent === prevIsPresent) {
        return;
      }
      if (isPresent && prevIsPresent === false) {
        if (this.isExitComplete) {
          const { initial, custom } = this.node.getProps();
          if (typeof initial === "string") {
            const resolved = resolveVariant(this.node, initial, custom);
            if (resolved) {
              const { transition, transitionEnd, ...target2 } = resolved;
              for (const key in target2) {
                (_a2 = this.node.getValue(key)) == null ? void 0 : _a2.jump(target2[key]);
              }
            }
          }
          this.node.animationState.reset();
          this.node.animationState.animateChanges();
        } else {
          this.node.animationState.setActive("exit", false);
        }
        this.isExitComplete = false;
        return;
      }
      const exitAnimation = this.node.animationState.setActive("exit", !isPresent);
      if (onExitComplete && !isPresent) {
        exitAnimation.then(() => {
          this.isExitComplete = true;
          onExitComplete(this.id);
        });
      }
    }
    mount() {
      const { register, onExitComplete } = this.node.presenceContext || {};
      if (onExitComplete) {
        onExitComplete(this.id);
      }
      if (register) {
        this.unmount = register(this.id);
      }
    }
    unmount() {
    }
  }
  const animations = {
    animation: {
      Feature: AnimationFeature
    },
    exit: {
      Feature: ExitAnimationFeature
    }
  };
  function extractEventInfo(event) {
    return {
      point: {
        x: event.pageX,
        y: event.pageY
      }
    };
  }
  const addPointerInfo = (handler) => (event) => isPrimaryPointer(event) && handler(event, extractEventInfo(event));
  function addPointerEvent(target2, eventName, handler, options) {
    return addDomEvent(target2, eventName, addPointerInfo(handler), options);
  }
  const getContextWindow = ({ current }) => {
    return current ? current.ownerDocument.defaultView : null;
  };
  const distance = (a, b) => Math.abs(a - b);
  function distance2D(a, b) {
    const xDelta = distance(a.x, b.x);
    const yDelta = distance(a.y, b.y);
    return Math.sqrt(xDelta ** 2 + yDelta ** 2);
  }
  const overflowStyles = /* @__PURE__ */ new Set(["auto", "scroll"]);
  class PanSession {
    constructor(event, handlers, { transformPagePoint, contextWindow = window, dragSnapToOrigin = false, distanceThreshold = 3, element } = {}) {
      this.startEvent = null;
      this.lastMoveEvent = null;
      this.lastMoveEventInfo = null;
      this.lastRawMoveEventInfo = null;
      this.handlers = {};
      this.contextWindow = window;
      this.scrollPositions = /* @__PURE__ */ new Map();
      this.removeScrollListeners = null;
      this.onElementScroll = (event2) => {
        this.handleScroll(event2.target);
      };
      this.onWindowScroll = () => {
        this.handleScroll(window);
      };
      this.updatePoint = () => {
        if (!(this.lastMoveEvent && this.lastMoveEventInfo))
          return;
        if (this.lastRawMoveEventInfo) {
          this.lastMoveEventInfo = transformPoint(this.lastRawMoveEventInfo, this.transformPagePoint);
        }
        const info2 = getPanInfo(this.lastMoveEventInfo, this.history);
        const isPanStarted = this.startEvent !== null;
        const isDistancePastThreshold = distance2D(info2.offset, { x: 0, y: 0 }) >= this.distanceThreshold;
        if (!isPanStarted && !isDistancePastThreshold)
          return;
        const { point: point2 } = info2;
        const { timestamp: timestamp2 } = frameData;
        this.history.push({ ...point2, timestamp: timestamp2 });
        const { onStart, onMove } = this.handlers;
        if (!isPanStarted) {
          onStart && onStart(this.lastMoveEvent, info2);
          this.startEvent = this.lastMoveEvent;
        }
        onMove && onMove(this.lastMoveEvent, info2);
      };
      this.handlePointerMove = (event2, info2) => {
        this.lastMoveEvent = event2;
        this.lastRawMoveEventInfo = info2;
        this.lastMoveEventInfo = transformPoint(info2, this.transformPagePoint);
        frame.update(this.updatePoint, true);
      };
      this.handlePointerUp = (event2, info2) => {
        this.end();
        const { onEnd, onSessionEnd, resumeAnimation } = this.handlers;
        if (this.dragSnapToOrigin || !this.startEvent) {
          resumeAnimation && resumeAnimation();
        }
        if (!(this.lastMoveEvent && this.lastMoveEventInfo))
          return;
        const panInfo = getPanInfo(event2.type === "pointercancel" ? this.lastMoveEventInfo : transformPoint(info2, this.transformPagePoint), this.history);
        if (this.startEvent && onEnd) {
          onEnd(event2, panInfo);
        }
        onSessionEnd && onSessionEnd(event2, panInfo);
      };
      if (!isPrimaryPointer(event))
        return;
      this.dragSnapToOrigin = dragSnapToOrigin;
      this.handlers = handlers;
      this.transformPagePoint = transformPagePoint;
      this.distanceThreshold = distanceThreshold;
      this.contextWindow = contextWindow || window;
      const info = extractEventInfo(event);
      const initialInfo = transformPoint(info, this.transformPagePoint);
      const { point } = initialInfo;
      const { timestamp } = frameData;
      this.history = [{ ...point, timestamp }];
      const { onSessionStart } = handlers;
      onSessionStart && onSessionStart(event, getPanInfo(initialInfo, this.history));
      this.removeListeners = pipe(addPointerEvent(this.contextWindow, "pointermove", this.handlePointerMove), addPointerEvent(this.contextWindow, "pointerup", this.handlePointerUp), addPointerEvent(this.contextWindow, "pointercancel", this.handlePointerUp));
      if (element) {
        this.startScrollTracking(element);
      }
    }
    /**
     * Start tracking scroll on ancestors and window.
     */
    startScrollTracking(element) {
      let current = element.parentElement;
      while (current) {
        const style = getComputedStyle(current);
        if (overflowStyles.has(style.overflowX) || overflowStyles.has(style.overflowY)) {
          this.scrollPositions.set(current, {
            x: current.scrollLeft,
            y: current.scrollTop
          });
        }
        current = current.parentElement;
      }
      this.scrollPositions.set(window, {
        x: window.scrollX,
        y: window.scrollY
      });
      window.addEventListener("scroll", this.onElementScroll, {
        capture: true
      });
      window.addEventListener("scroll", this.onWindowScroll);
      this.removeScrollListeners = () => {
        window.removeEventListener("scroll", this.onElementScroll, {
          capture: true
        });
        window.removeEventListener("scroll", this.onWindowScroll);
      };
    }
    /**
     * Handle scroll compensation during drag.
     *
     * For element scroll: adjusts history origin since pageX/pageY doesn't change.
     * For window scroll: adjusts lastMoveEventInfo since pageX/pageY would change.
     */
    handleScroll(target2) {
      const initial = this.scrollPositions.get(target2);
      if (!initial)
        return;
      const isWindow = target2 === window;
      const current = isWindow ? { x: window.scrollX, y: window.scrollY } : {
        x: target2.scrollLeft,
        y: target2.scrollTop
      };
      const delta = { x: current.x - initial.x, y: current.y - initial.y };
      if (delta.x === 0 && delta.y === 0)
        return;
      if (isWindow) {
        if (this.lastMoveEventInfo) {
          this.lastMoveEventInfo.point.x += delta.x;
          this.lastMoveEventInfo.point.y += delta.y;
        }
      } else {
        if (this.history.length > 0) {
          this.history[0].x -= delta.x;
          this.history[0].y -= delta.y;
        }
      }
      this.scrollPositions.set(target2, current);
      frame.update(this.updatePoint, true);
    }
    updateHandlers(handlers) {
      this.handlers = handlers;
    }
    end() {
      this.removeListeners && this.removeListeners();
      this.removeScrollListeners && this.removeScrollListeners();
      this.scrollPositions.clear();
      cancelFrame(this.updatePoint);
    }
  }
  function transformPoint(info, transformPagePoint) {
    return transformPagePoint ? { point: transformPagePoint(info.point) } : info;
  }
  function subtractPoint(a, b) {
    return { x: a.x - b.x, y: a.y - b.y };
  }
  function getPanInfo({ point }, history) {
    return {
      point,
      delta: subtractPoint(point, lastDevicePoint(history)),
      offset: subtractPoint(point, startDevicePoint(history)),
      velocity: getVelocity(history, 0.1)
    };
  }
  function startDevicePoint(history) {
    return history[0];
  }
  function lastDevicePoint(history) {
    return history[history.length - 1];
  }
  function getVelocity(history, timeDelta) {
    if (history.length < 2) {
      return { x: 0, y: 0 };
    }
    let i = history.length - 1;
    let timestampedPoint = null;
    const lastPoint = lastDevicePoint(history);
    while (i >= 0) {
      timestampedPoint = history[i];
      if (lastPoint.timestamp - timestampedPoint.timestamp > /* @__PURE__ */ secondsToMilliseconds(timeDelta)) {
        break;
      }
      i--;
    }
    if (!timestampedPoint) {
      return { x: 0, y: 0 };
    }
    if (timestampedPoint === history[0] && history.length > 2 && lastPoint.timestamp - timestampedPoint.timestamp > /* @__PURE__ */ secondsToMilliseconds(timeDelta) * 2) {
      timestampedPoint = history[1];
    }
    const time2 = /* @__PURE__ */ millisecondsToSeconds(lastPoint.timestamp - timestampedPoint.timestamp);
    if (time2 === 0) {
      return { x: 0, y: 0 };
    }
    const currentVelocity = {
      x: (lastPoint.x - timestampedPoint.x) / time2,
      y: (lastPoint.y - timestampedPoint.y) / time2
    };
    if (currentVelocity.x === Infinity) {
      currentVelocity.x = 0;
    }
    if (currentVelocity.y === Infinity) {
      currentVelocity.y = 0;
    }
    return currentVelocity;
  }
  function applyConstraints(point, { min, max }, elastic) {
    if (min !== void 0 && point < min) {
      point = elastic ? mixNumber$1(min, point, elastic.min) : Math.max(point, min);
    } else if (max !== void 0 && point > max) {
      point = elastic ? mixNumber$1(max, point, elastic.max) : Math.min(point, max);
    }
    return point;
  }
  function calcRelativeAxisConstraints(axis, min, max) {
    return {
      min: min !== void 0 ? axis.min + min : void 0,
      max: max !== void 0 ? axis.max + max - (axis.max - axis.min) : void 0
    };
  }
  function calcRelativeConstraints(layoutBox, { top, left, bottom, right }) {
    return {
      x: calcRelativeAxisConstraints(layoutBox.x, left, right),
      y: calcRelativeAxisConstraints(layoutBox.y, top, bottom)
    };
  }
  function calcViewportAxisConstraints(layoutAxis, constraintsAxis) {
    let min = constraintsAxis.min - layoutAxis.min;
    let max = constraintsAxis.max - layoutAxis.max;
    if (constraintsAxis.max - constraintsAxis.min < layoutAxis.max - layoutAxis.min) {
      [min, max] = [max, min];
    }
    return { min, max };
  }
  function calcViewportConstraints(layoutBox, constraintsBox) {
    return {
      x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x),
      y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y)
    };
  }
  function calcOrigin(source, target2) {
    let origin = 0.5;
    const sourceLength = calcLength(source);
    const targetLength = calcLength(target2);
    if (targetLength > sourceLength) {
      origin = /* @__PURE__ */ progress$1(target2.min, target2.max - sourceLength, source.min);
    } else if (sourceLength > targetLength) {
      origin = /* @__PURE__ */ progress$1(source.min, source.max - targetLength, target2.min);
    }
    return clamp(0, 1, origin);
  }
  function rebaseAxisConstraints(layout2, constraints) {
    const relativeConstraints = {};
    if (constraints.min !== void 0) {
      relativeConstraints.min = constraints.min - layout2.min;
    }
    if (constraints.max !== void 0) {
      relativeConstraints.max = constraints.max - layout2.min;
    }
    return relativeConstraints;
  }
  const defaultElastic = 0.35;
  function resolveDragElastic(dragElastic = defaultElastic) {
    if (dragElastic === false) {
      dragElastic = 0;
    } else if (dragElastic === true) {
      dragElastic = defaultElastic;
    }
    return {
      x: resolveAxisElastic(dragElastic, "left", "right"),
      y: resolveAxisElastic(dragElastic, "top", "bottom")
    };
  }
  function resolveAxisElastic(dragElastic, minLabel, maxLabel) {
    return {
      min: resolvePointElastic(dragElastic, minLabel),
      max: resolvePointElastic(dragElastic, maxLabel)
    };
  }
  function resolvePointElastic(dragElastic, label2) {
    return typeof dragElastic === "number" ? dragElastic : dragElastic[label2] || 0;
  }
  const elementDragControls = /* @__PURE__ */ new WeakMap();
  class VisualElementDragControls {
    constructor(visualElement) {
      this.openDragLock = null;
      this.isDragging = false;
      this.currentDirection = null;
      this.originPoint = { x: 0, y: 0 };
      this.constraints = false;
      this.hasMutatedConstraints = false;
      this.elastic = createBox();
      this.latestPointerEvent = null;
      this.latestPanInfo = null;
      this.visualElement = visualElement;
    }
    start(originEvent, { snapToCursor = false, distanceThreshold } = {}) {
      const { presenceContext } = this.visualElement;
      if (presenceContext && presenceContext.isPresent === false)
        return;
      const onSessionStart = (event) => {
        if (snapToCursor) {
          this.snapToCursor(extractEventInfo(event).point);
        }
        this.stopAnimation();
      };
      const onStart = (event, info) => {
        const { drag: drag2, dragPropagation, onDragStart } = this.getProps();
        if (drag2 && !dragPropagation) {
          if (this.openDragLock)
            this.openDragLock();
          this.openDragLock = setDragLock(drag2);
          if (!this.openDragLock)
            return;
        }
        this.latestPointerEvent = event;
        this.latestPanInfo = info;
        this.isDragging = true;
        this.currentDirection = null;
        this.resolveConstraints();
        if (this.visualElement.projection) {
          this.visualElement.projection.isAnimationBlocked = true;
          this.visualElement.projection.target = void 0;
        }
        eachAxis((axis) => {
          let current = this.getAxisMotionValue(axis).get() || 0;
          if (percent.test(current)) {
            const { projection } = this.visualElement;
            if (projection && projection.layout) {
              const measuredAxis = projection.layout.layoutBox[axis];
              if (measuredAxis) {
                const length = calcLength(measuredAxis);
                current = length * (parseFloat(current) / 100);
              }
            }
          }
          this.originPoint[axis] = current;
        });
        if (onDragStart) {
          frame.update(() => onDragStart(event, info), false, true);
        }
        addValueToWillChange(this.visualElement, "transform");
        const { animationState } = this.visualElement;
        animationState && animationState.setActive("whileDrag", true);
      };
      const onMove = (event, info) => {
        this.latestPointerEvent = event;
        this.latestPanInfo = info;
        const { dragPropagation, dragDirectionLock, onDirectionLock, onDrag } = this.getProps();
        if (!dragPropagation && !this.openDragLock)
          return;
        const { offset } = info;
        if (dragDirectionLock && this.currentDirection === null) {
          this.currentDirection = getCurrentDirection(offset);
          if (this.currentDirection !== null) {
            onDirectionLock && onDirectionLock(this.currentDirection);
          }
          return;
        }
        this.updateAxis("x", info.point, offset);
        this.updateAxis("y", info.point, offset);
        this.visualElement.render();
        if (onDrag) {
          frame.update(() => onDrag(event, info), false, true);
        }
      };
      const onSessionEnd = (event, info) => {
        this.latestPointerEvent = event;
        this.latestPanInfo = info;
        this.stop(event, info);
        this.latestPointerEvent = null;
        this.latestPanInfo = null;
      };
      const resumeAnimation = () => {
        const { dragSnapToOrigin: snap } = this.getProps();
        if (snap || this.constraints) {
          this.startAnimation({ x: 0, y: 0 });
        }
      };
      const { dragSnapToOrigin } = this.getProps();
      this.panSession = new PanSession(originEvent, {
        onSessionStart,
        onStart,
        onMove,
        onSessionEnd,
        resumeAnimation
      }, {
        transformPagePoint: this.visualElement.getTransformPagePoint(),
        dragSnapToOrigin,
        distanceThreshold,
        contextWindow: getContextWindow(this.visualElement),
        element: this.visualElement.current
      });
    }
    /**
     * @internal
     */
    stop(event, panInfo) {
      const finalEvent = event || this.latestPointerEvent;
      const finalPanInfo = panInfo || this.latestPanInfo;
      const isDragging2 = this.isDragging;
      this.cancel();
      if (!isDragging2 || !finalPanInfo || !finalEvent)
        return;
      const { velocity } = finalPanInfo;
      this.startAnimation(velocity);
      const { onDragEnd } = this.getProps();
      if (onDragEnd) {
        frame.postRender(() => onDragEnd(finalEvent, finalPanInfo));
      }
    }
    /**
     * @internal
     */
    cancel() {
      this.isDragging = false;
      const { projection, animationState } = this.visualElement;
      if (projection) {
        projection.isAnimationBlocked = false;
      }
      this.endPanSession();
      const { dragPropagation } = this.getProps();
      if (!dragPropagation && this.openDragLock) {
        this.openDragLock();
        this.openDragLock = null;
      }
      animationState && animationState.setActive("whileDrag", false);
    }
    /**
     * Clean up the pan session without modifying other drag state.
     * This is used during unmount to ensure event listeners are removed
     * without affecting projection animations or drag locks.
     * @internal
     */
    endPanSession() {
      this.panSession && this.panSession.end();
      this.panSession = void 0;
    }
    updateAxis(axis, _point, offset) {
      const { drag: drag2 } = this.getProps();
      if (!offset || !shouldDrag(axis, drag2, this.currentDirection))
        return;
      const axisValue = this.getAxisMotionValue(axis);
      let next = this.originPoint[axis] + offset[axis];
      if (this.constraints && this.constraints[axis]) {
        next = applyConstraints(next, this.constraints[axis], this.elastic[axis]);
      }
      axisValue.set(next);
    }
    resolveConstraints() {
      var _a2;
      const { dragConstraints, dragElastic } = this.getProps();
      const layout2 = this.visualElement.projection && !this.visualElement.projection.layout ? this.visualElement.projection.measure(false) : (_a2 = this.visualElement.projection) == null ? void 0 : _a2.layout;
      const prevConstraints = this.constraints;
      if (dragConstraints && isRefObject(dragConstraints)) {
        if (!this.constraints) {
          this.constraints = this.resolveRefConstraints();
        }
      } else {
        if (dragConstraints && layout2) {
          this.constraints = calcRelativeConstraints(layout2.layoutBox, dragConstraints);
        } else {
          this.constraints = false;
        }
      }
      this.elastic = resolveDragElastic(dragElastic);
      if (prevConstraints !== this.constraints && !isRefObject(dragConstraints) && layout2 && this.constraints && !this.hasMutatedConstraints) {
        eachAxis((axis) => {
          if (this.constraints !== false && this.getAxisMotionValue(axis)) {
            this.constraints[axis] = rebaseAxisConstraints(layout2.layoutBox[axis], this.constraints[axis]);
          }
        });
      }
    }
    resolveRefConstraints() {
      const { dragConstraints: constraints, onMeasureDragConstraints } = this.getProps();
      if (!constraints || !isRefObject(constraints))
        return false;
      const constraintsElement = constraints.current;
      invariant(constraintsElement !== null, "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.", "drag-constraints-ref");
      const { projection } = this.visualElement;
      if (!projection || !projection.layout)
        return false;
      const constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint());
      let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, constraintsBox);
      if (onMeasureDragConstraints) {
        const userConstraints = onMeasureDragConstraints(convertBoxToBoundingBox(measuredConstraints));
        this.hasMutatedConstraints = !!userConstraints;
        if (userConstraints) {
          measuredConstraints = convertBoundingBoxToBox(userConstraints);
        }
      }
      return measuredConstraints;
    }
    startAnimation(velocity) {
      const { drag: drag2, dragMomentum, dragElastic, dragTransition, dragSnapToOrigin, onDragTransitionEnd } = this.getProps();
      const constraints = this.constraints || {};
      const momentumAnimations = eachAxis((axis) => {
        if (!shouldDrag(axis, drag2, this.currentDirection)) {
          return;
        }
        let transition = constraints && constraints[axis] || {};
        if (dragSnapToOrigin === true || dragSnapToOrigin === axis)
          transition = { min: 0, max: 0 };
        const bounceStiffness = dragElastic ? 200 : 1e6;
        const bounceDamping = dragElastic ? 40 : 1e7;
        const inertia2 = {
          type: "inertia",
          velocity: dragMomentum ? velocity[axis] : 0,
          bounceStiffness,
          bounceDamping,
          timeConstant: 750,
          restDelta: 1,
          restSpeed: 10,
          ...dragTransition,
          ...transition
        };
        return this.startAxisValueAnimation(axis, inertia2);
      });
      return Promise.all(momentumAnimations).then(onDragTransitionEnd);
    }
    startAxisValueAnimation(axis, transition) {
      const axisValue = this.getAxisMotionValue(axis);
      addValueToWillChange(this.visualElement, axis);
      return axisValue.start(animateMotionValue(axis, axisValue, 0, transition, this.visualElement, false));
    }
    stopAnimation() {
      eachAxis((axis) => this.getAxisMotionValue(axis).stop());
    }
    /**
     * Drag works differently depending on which props are provided.
     *
     * - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values.
     * - Otherwise, we apply the delta to the x/y motion values.
     */
    getAxisMotionValue(axis) {
      const dragKey = `_drag${axis.toUpperCase()}`;
      const props = this.visualElement.getProps();
      const externalMotionValue = props[dragKey];
      return externalMotionValue ? externalMotionValue : this.visualElement.getValue(axis, (props.initial ? props.initial[axis] : void 0) || 0);
    }
    snapToCursor(point) {
      eachAxis((axis) => {
        const { drag: drag2 } = this.getProps();
        if (!shouldDrag(axis, drag2, this.currentDirection))
          return;
        const { projection } = this.visualElement;
        const axisValue = this.getAxisMotionValue(axis);
        if (projection && projection.layout) {
          const { min, max } = projection.layout.layoutBox[axis];
          const current = axisValue.get() || 0;
          axisValue.set(point[axis] - mixNumber$1(min, max, 0.5) + current);
        }
      });
    }
    /**
     * When the viewport resizes we want to check if the measured constraints
     * have changed and, if so, reposition the element within those new constraints
     * relative to where it was before the resize.
     */
    scalePositionWithinConstraints() {
      if (!this.visualElement.current)
        return;
      const { drag: drag2, dragConstraints } = this.getProps();
      const { projection } = this.visualElement;
      if (!isRefObject(dragConstraints) || !projection || !this.constraints)
        return;
      this.stopAnimation();
      const boxProgress = { x: 0, y: 0 };
      eachAxis((axis) => {
        const axisValue = this.getAxisMotionValue(axis);
        if (axisValue && this.constraints !== false) {
          const latest = axisValue.get();
          boxProgress[axis] = calcOrigin({ min: latest, max: latest }, this.constraints[axis]);
        }
      });
      const { transformTemplate } = this.visualElement.getProps();
      this.visualElement.current.style.transform = transformTemplate ? transformTemplate({}, "") : "none";
      projection.root && projection.root.updateScroll();
      projection.updateLayout();
      this.constraints = false;
      this.resolveConstraints();
      eachAxis((axis) => {
        if (!shouldDrag(axis, drag2, null))
          return;
        const axisValue = this.getAxisMotionValue(axis);
        const { min, max } = this.constraints[axis];
        axisValue.set(mixNumber$1(min, max, boxProgress[axis]));
      });
      this.visualElement.render();
    }
    addListeners() {
      if (!this.visualElement.current)
        return;
      elementDragControls.set(this.visualElement, this);
      const element = this.visualElement.current;
      const stopPointerListener = addPointerEvent(element, "pointerdown", (event) => {
        const { drag: drag2, dragListener = true } = this.getProps();
        const target2 = event.target;
        const isClickingTextInputChild = target2 !== element && isElementTextInput(target2);
        if (drag2 && dragListener && !isClickingTextInputChild) {
          this.start(event);
        }
      });
      let stopResizeObservers;
      const measureDragConstraints = () => {
        const { dragConstraints } = this.getProps();
        if (isRefObject(dragConstraints) && dragConstraints.current) {
          this.constraints = this.resolveRefConstraints();
          if (!stopResizeObservers) {
            stopResizeObservers = startResizeObservers(element, dragConstraints.current, () => this.scalePositionWithinConstraints());
          }
        }
      };
      const { projection } = this.visualElement;
      const stopMeasureLayoutListener = projection.addEventListener("measure", measureDragConstraints);
      if (projection && !projection.layout) {
        projection.root && projection.root.updateScroll();
        projection.updateLayout();
      }
      frame.read(measureDragConstraints);
      const stopResizeListener = addDomEvent(window, "resize", () => this.scalePositionWithinConstraints());
      const stopLayoutUpdateListener = projection.addEventListener("didUpdate", (({ delta, hasLayoutChanged }) => {
        if (this.isDragging && hasLayoutChanged) {
          eachAxis((axis) => {
            const motionValue2 = this.getAxisMotionValue(axis);
            if (!motionValue2)
              return;
            this.originPoint[axis] += delta[axis].translate;
            motionValue2.set(motionValue2.get() + delta[axis].translate);
          });
          this.visualElement.render();
        }
      }));
      return () => {
        stopResizeListener();
        stopPointerListener();
        stopMeasureLayoutListener();
        stopLayoutUpdateListener && stopLayoutUpdateListener();
        stopResizeObservers && stopResizeObservers();
      };
    }
    getProps() {
      const props = this.visualElement.getProps();
      const { drag: drag2 = false, dragDirectionLock = false, dragPropagation = false, dragConstraints = false, dragElastic = defaultElastic, dragMomentum = true } = props;
      return {
        ...props,
        drag: drag2,
        dragDirectionLock,
        dragPropagation,
        dragConstraints,
        dragElastic,
        dragMomentum
      };
    }
  }
  function skipFirstCall(callback) {
    let isFirst = true;
    return () => {
      if (isFirst) {
        isFirst = false;
        return;
      }
      callback();
    };
  }
  function startResizeObservers(element, constraintsElement, onResize) {
    const stopElement = resize(element, skipFirstCall(onResize));
    const stopContainer = resize(constraintsElement, skipFirstCall(onResize));
    return () => {
      stopElement();
      stopContainer();
    };
  }
  function shouldDrag(direction, drag2, currentDirection) {
    return (drag2 === true || drag2 === direction) && (currentDirection === null || currentDirection === direction);
  }
  function getCurrentDirection(offset, lockThreshold = 10) {
    let direction = null;
    if (Math.abs(offset.y) > lockThreshold) {
      direction = "y";
    } else if (Math.abs(offset.x) > lockThreshold) {
      direction = "x";
    }
    return direction;
  }
  class DragGesture extends Feature {
    constructor(node) {
      super(node);
      this.removeGroupControls = noop;
      this.removeListeners = noop;
      this.controls = new VisualElementDragControls(node);
    }
    mount() {
      const { dragControls } = this.node.getProps();
      if (dragControls) {
        this.removeGroupControls = dragControls.subscribe(this.controls);
      }
      this.removeListeners = this.controls.addListeners() || noop;
    }
    update() {
      const { dragControls } = this.node.getProps();
      const { dragControls: prevDragControls } = this.node.prevProps || {};
      if (dragControls !== prevDragControls) {
        this.removeGroupControls();
        if (dragControls) {
          this.removeGroupControls = dragControls.subscribe(this.controls);
        }
      }
    }
    unmount() {
      this.removeGroupControls();
      this.removeListeners();
      if (!this.controls.isDragging) {
        this.controls.endPanSession();
      }
    }
  }
  const asyncHandler = (handler) => (event, info) => {
    if (handler) {
      frame.update(() => handler(event, info), false, true);
    }
  };
  class PanGesture extends Feature {
    constructor() {
      super(...arguments);
      this.removePointerDownListener = noop;
    }
    onPointerDown(pointerDownEvent) {
      this.session = new PanSession(pointerDownEvent, this.createPanHandlers(), {
        transformPagePoint: this.node.getTransformPagePoint(),
        contextWindow: getContextWindow(this.node)
      });
    }
    createPanHandlers() {
      const { onPanSessionStart, onPanStart, onPan, onPanEnd } = this.node.getProps();
      return {
        onSessionStart: asyncHandler(onPanSessionStart),
        onStart: asyncHandler(onPanStart),
        onMove: asyncHandler(onPan),
        onEnd: (event, info) => {
          delete this.session;
          if (onPanEnd) {
            frame.postRender(() => onPanEnd(event, info));
          }
        }
      };
    }
    mount() {
      this.removePointerDownListener = addPointerEvent(this.node.current, "pointerdown", (event) => this.onPointerDown(event));
    }
    update() {
      this.session && this.session.updateHandlers(this.createPanHandlers());
    }
    unmount() {
      this.removePointerDownListener();
      this.session && this.session.end();
    }
  }
  let hasTakenAnySnapshot = false;
  class MeasureLayoutWithContext extends reactExports.Component {
    /**
     * This only mounts projection nodes for components that
     * need measuring, we might want to do it for all components
     * in order to incorporate transforms
     */
    componentDidMount() {
      const { visualElement, layoutGroup, switchLayoutGroup, layoutId } = this.props;
      const { projection } = visualElement;
      if (projection) {
        if (layoutGroup.group)
          layoutGroup.group.add(projection);
        if (switchLayoutGroup && switchLayoutGroup.register && layoutId) {
          switchLayoutGroup.register(projection);
        }
        if (hasTakenAnySnapshot) {
          projection.root.didUpdate();
        }
        projection.addEventListener("animationComplete", () => {
          this.safeToRemove();
        });
        projection.setOptions({
          ...projection.options,
          layoutDependency: this.props.layoutDependency,
          onExitComplete: () => this.safeToRemove()
        });
      }
      globalProjectionState.hasEverUpdated = true;
    }
    getSnapshotBeforeUpdate(prevProps) {
      const { layoutDependency, visualElement, drag: drag2, isPresent } = this.props;
      const { projection } = visualElement;
      if (!projection)
        return null;
      projection.isPresent = isPresent;
      if (prevProps.layoutDependency !== layoutDependency) {
        projection.setOptions({
          ...projection.options,
          layoutDependency
        });
      }
      hasTakenAnySnapshot = true;
      if (drag2 || prevProps.layoutDependency !== layoutDependency || layoutDependency === void 0 || prevProps.isPresent !== isPresent) {
        projection.willUpdate();
      } else {
        this.safeToRemove();
      }
      if (prevProps.isPresent !== isPresent) {
        if (isPresent) {
          projection.promote();
        } else if (!projection.relegate()) {
          frame.postRender(() => {
            const stack = projection.getStack();
            if (!stack || !stack.members.length) {
              this.safeToRemove();
            }
          });
        }
      }
      return null;
    }
    componentDidUpdate() {
      const { visualElement, layoutAnchor } = this.props;
      const { projection } = visualElement;
      if (projection) {
        projection.options.layoutAnchor = layoutAnchor;
        projection.root.didUpdate();
        microtask.postRender(() => {
          if (!projection.currentAnimation && projection.isLead()) {
            this.safeToRemove();
          }
        });
      }
    }
    componentWillUnmount() {
      const { visualElement, layoutGroup, switchLayoutGroup: promoteContext } = this.props;
      const { projection } = visualElement;
      hasTakenAnySnapshot = true;
      if (projection) {
        projection.scheduleCheckAfterUnmount();
        if (layoutGroup && layoutGroup.group)
          layoutGroup.group.remove(projection);
        if (promoteContext && promoteContext.deregister)
          promoteContext.deregister(projection);
      }
    }
    safeToRemove() {
      const { safeToRemove } = this.props;
      safeToRemove && safeToRemove();
    }
    render() {
      return null;
    }
  }
  function MeasureLayout(props) {
    const [isPresent, safeToRemove] = usePresence();
    const layoutGroup = reactExports.useContext(LayoutGroupContext);
    return jsxRuntimeExports.jsx(MeasureLayoutWithContext, { ...props, layoutGroup, switchLayoutGroup: reactExports.useContext(SwitchLayoutGroupContext), isPresent, safeToRemove });
  }
  const drag = {
    pan: {
      Feature: PanGesture
    },
    drag: {
      Feature: DragGesture,
      ProjectionNode: HTMLProjectionNode,
      MeasureLayout
    }
  };
  function handleHoverEvent(node, event, lifecycle) {
    const { props } = node;
    if (node.animationState && props.whileHover) {
      node.animationState.setActive("whileHover", lifecycle === "Start");
    }
    const eventName = "onHover" + lifecycle;
    const callback = props[eventName];
    if (callback) {
      frame.postRender(() => callback(event, extractEventInfo(event)));
    }
  }
  class HoverGesture extends Feature {
    mount() {
      const { current } = this.node;
      if (!current)
        return;
      this.unmount = hover(current, (_element, startEvent) => {
        handleHoverEvent(this.node, startEvent, "Start");
        return (endEvent) => handleHoverEvent(this.node, endEvent, "End");
      });
    }
    unmount() {
    }
  }
  class FocusGesture extends Feature {
    constructor() {
      super(...arguments);
      this.isActive = false;
    }
    onFocus() {
      let isFocusVisible = false;
      try {
        isFocusVisible = this.node.current.matches(":focus-visible");
      } catch (e) {
        isFocusVisible = true;
      }
      if (!isFocusVisible || !this.node.animationState)
        return;
      this.node.animationState.setActive("whileFocus", true);
      this.isActive = true;
    }
    onBlur() {
      if (!this.isActive || !this.node.animationState)
        return;
      this.node.animationState.setActive("whileFocus", false);
      this.isActive = false;
    }
    mount() {
      this.unmount = pipe(addDomEvent(this.node.current, "focus", () => this.onFocus()), addDomEvent(this.node.current, "blur", () => this.onBlur()));
    }
    unmount() {
    }
  }
  function handlePressEvent(node, event, lifecycle) {
    const { props } = node;
    if (node.current instanceof HTMLButtonElement && node.current.disabled) {
      return;
    }
    if (node.animationState && props.whileTap) {
      node.animationState.setActive("whileTap", lifecycle === "Start");
    }
    const eventName = "onTap" + (lifecycle === "End" ? "" : lifecycle);
    const callback = props[eventName];
    if (callback) {
      frame.postRender(() => callback(event, extractEventInfo(event)));
    }
  }
  class PressGesture extends Feature {
    mount() {
      const { current } = this.node;
      if (!current)
        return;
      const { globalTapTarget, propagate } = this.node.props;
      this.unmount = press(current, (_element, startEvent) => {
        handlePressEvent(this.node, startEvent, "Start");
        return (endEvent, { success }) => handlePressEvent(this.node, endEvent, success ? "End" : "Cancel");
      }, {
        useGlobalTarget: globalTapTarget,
        stopPropagation: (propagate == null ? void 0 : propagate.tap) === false
      });
    }
    unmount() {
    }
  }
  const observerCallbacks = /* @__PURE__ */ new WeakMap();
  const observers = /* @__PURE__ */ new WeakMap();
  const fireObserverCallback = (entry) => {
    const callback = observerCallbacks.get(entry.target);
    callback && callback(entry);
  };
  const fireAllObserverCallbacks = (entries) => {
    entries.forEach(fireObserverCallback);
  };
  function initIntersectionObserver({ root: root2, ...options }) {
    const lookupRoot = root2 || document;
    if (!observers.has(lookupRoot)) {
      observers.set(lookupRoot, {});
    }
    const rootObservers = observers.get(lookupRoot);
    const key = JSON.stringify(options);
    if (!rootObservers[key]) {
      rootObservers[key] = new IntersectionObserver(fireAllObserverCallbacks, { root: root2, ...options });
    }
    return rootObservers[key];
  }
  function observeIntersection(element, options, callback) {
    const rootInteresectionObserver = initIntersectionObserver(options);
    observerCallbacks.set(element, callback);
    rootInteresectionObserver.observe(element);
    return () => {
      observerCallbacks.delete(element);
      rootInteresectionObserver.unobserve(element);
    };
  }
  const thresholdNames = {
    some: 0,
    all: 1
  };
  class InViewFeature extends Feature {
    constructor() {
      super(...arguments);
      this.hasEnteredView = false;
      this.isInView = false;
    }
    startObserver() {
      var _a2;
      (_a2 = this.stopObserver) == null ? void 0 : _a2.call(this);
      const { viewport = {} } = this.node.getProps();
      const { root: root2, margin: rootMargin, amount = "some", once } = viewport;
      const options = {
        root: root2 ? root2.current : void 0,
        rootMargin,
        threshold: typeof amount === "number" ? amount : thresholdNames[amount]
      };
      const onIntersectionUpdate = (entry) => {
        const { isIntersecting } = entry;
        if (this.isInView === isIntersecting)
          return;
        this.isInView = isIntersecting;
        if (once && !isIntersecting && this.hasEnteredView) {
          return;
        } else if (isIntersecting) {
          this.hasEnteredView = true;
        }
        if (this.node.animationState) {
          this.node.animationState.setActive("whileInView", isIntersecting);
        }
        const { onViewportEnter, onViewportLeave } = this.node.getProps();
        const callback = isIntersecting ? onViewportEnter : onViewportLeave;
        callback && callback(entry);
      };
      this.stopObserver = observeIntersection(this.node.current, options, onIntersectionUpdate);
    }
    mount() {
      this.startObserver();
    }
    update() {
      if (typeof IntersectionObserver === "undefined")
        return;
      const { props, prevProps } = this.node;
      const hasOptionsChanged = ["amount", "margin", "root"].some(hasViewportOptionChanged(props, prevProps));
      if (hasOptionsChanged) {
        this.startObserver();
      }
    }
    unmount() {
      var _a2;
      (_a2 = this.stopObserver) == null ? void 0 : _a2.call(this);
      this.hasEnteredView = false;
      this.isInView = false;
    }
  }
  function hasViewportOptionChanged({ viewport = {} }, { viewport: prevViewport = {} } = {}) {
    return (name2) => viewport[name2] !== prevViewport[name2];
  }
  const gestureAnimations = {
    inView: {
      Feature: InViewFeature
    },
    tap: {
      Feature: PressGesture
    },
    focus: {
      Feature: FocusGesture
    },
    hover: {
      Feature: HoverGesture
    }
  };
  const layout = {
    layout: {
      ProjectionNode: HTMLProjectionNode,
      MeasureLayout
    }
  };
  const featureBundle = {
    ...animations,
    ...gestureAnimations,
    ...drag,
    ...layout
  };
  const motion = /* @__PURE__ */ createMotionProxy(featureBundle, createDomVisualElement);
  function useMotionValue(initial) {
    const value = useConstant(() => motionValue(initial));
    const { isStatic } = reactExports.useContext(MotionConfigContext);
    if (isStatic) {
      const [, setLatest] = reactExports.useState(initial);
      reactExports.useEffect(() => value.on("change", setLatest), []);
    }
    return value;
  }
  function useCombineMotionValues(values, combineValues) {
    const value = useMotionValue(combineValues());
    const updateValue = () => value.set(combineValues());
    updateValue();
    useIsomorphicLayoutEffect(() => {
      const scheduleUpdate = () => frame.preRender(updateValue, false, true);
      const subscriptions = values.map((v) => v.on("change", scheduleUpdate));
      return () => {
        subscriptions.forEach((unsubscribe) => unsubscribe());
        cancelFrame(updateValue);
      };
    });
    return value;
  }
  function useComputed(compute) {
    collectMotionValues.current = [];
    compute();
    const value = useCombineMotionValues(collectMotionValues.current, compute);
    collectMotionValues.current = void 0;
    return value;
  }
  function useTransform(input2, inputRangeOrTransformer, outputRangeOrMap, options) {
    if (typeof input2 === "function") {
      return useComputed(input2);
    }
    const outputRange = outputRangeOrMap;
    const transformer = transform(inputRangeOrTransformer, outputRange, options);
    const result = Array.isArray(input2) ? useListTransform(input2, transformer) : useListTransform([input2], ([latest]) => transformer(latest));
    const inputAccelerate = !Array.isArray(input2) ? input2.accelerate : void 0;
    if (inputAccelerate && !inputAccelerate.isTransformed && typeof inputRangeOrTransformer !== "function" && Array.isArray(outputRangeOrMap) && (options == null ? void 0 : options.clamp) !== false) {
      result.accelerate = {
        ...inputAccelerate,
        times: inputRangeOrTransformer,
        keyframes: outputRangeOrMap,
        isTransformed: true,
        ...{}
      };
    }
    return result;
  }
  function useListTransform(values, transformer) {
    const latest = useConstant(() => []);
    return useCombineMotionValues(values, () => {
      latest.length = 0;
      const numValues = values.length;
      for (let i = 0; i < numValues; i++) {
        latest[i] = values[i].get();
      }
      return transformer(latest);
    });
  }
  function useFollowValue(source, options = {}) {
    const { isStatic } = reactExports.useContext(MotionConfigContext);
    const getFromSource = () => isMotionValue(source) ? source.get() : source;
    if (isStatic) {
      return useTransform(getFromSource);
    }
    const value = useMotionValue(getFromSource());
    reactExports.useInsertionEffect(() => {
      return attachFollow(value, source, options);
    }, [value, JSON.stringify(options)]);
    return value;
  }
  function useSpring(source, options = {}) {
    return useFollowValue(source, { type: "spring", ...options });
  }
  const thresholds = {
    some: 0,
    all: 1
  };
  function inView(elementOrSelector, onStart, { root: root2, margin: rootMargin, amount = "some" } = {}) {
    const elements = resolveElements(elementOrSelector);
    const activeIntersections = /* @__PURE__ */ new WeakMap();
    const onIntersectionChange = (entries) => {
      entries.forEach((entry) => {
        const onEnd = activeIntersections.get(entry.target);
        if (entry.isIntersecting === Boolean(onEnd))
          return;
        if (entry.isIntersecting) {
          const newOnEnd = onStart(entry.target, entry);
          if (typeof newOnEnd === "function") {
            activeIntersections.set(entry.target, newOnEnd);
          } else {
            observer2.unobserve(entry.target);
          }
        } else if (typeof onEnd === "function") {
          onEnd(entry);
          activeIntersections.delete(entry.target);
        }
      });
    };
    const observer2 = new IntersectionObserver(onIntersectionChange, {
      root: root2,
      rootMargin,
      threshold: typeof amount === "number" ? amount : thresholds[amount]
    });
    elements.forEach((element) => observer2.observe(element));
    return () => observer2.disconnect();
  }
  function useInView(ref, { root: root2, margin, amount, once = false, initial = false } = {}) {
    const [isInView, setInView] = reactExports.useState(initial);
    reactExports.useEffect(() => {
      if (!ref.current || once && isInView)
        return;
      const onEnter = () => {
        setInView(true);
        return once ? void 0 : () => setInView(false);
      };
      const options = {
        root: root2 && root2.current || void 0,
        margin,
        amount
      };
      return inView(ref.current, onEnter, options);
    }, [root2, ref, margin, once, amount]);
    return isInView;
  }
  function cn(...classes) {
    return classes.filter(Boolean).join(" ");
  }
  function formatTickerValue(amount, decimalPlaces, prefix, suffix) {
    const formatted = Intl.NumberFormat("en-US", {
      minimumFractionDigits: decimalPlaces,
      maximumFractionDigits: decimalPlaces
    }).format(Number(amount.toFixed(decimalPlaces)));
    return `${prefix}${formatted}${suffix}`;
  }
  function NumberTicker({
    value,
    delay: delay2 = 0,
    className,
    decimalPlaces = 0,
    prefix = "",
    suffix = "",
    animate = true,
    onSettled,
    ...props
  }) {
    const ref = reactExports.useRef(null);
    const prevValue = reactExports.useRef(value);
    const settledRef = reactExports.useRef(false);
    const onSettledRef = reactExports.useRef(onSettled);
    onSettledRef.current = onSettled;
    const motionValue2 = useMotionValue(value);
    const springValue = useSpring(motionValue2, {
      damping: 60,
      stiffness: 100
    });
    reactExports.useEffect(() => {
      if (prevValue.current === value) return;
      const run = () => {
        var _a2;
        prevValue.current = value;
        settledRef.current = false;
        motionValue2.set(value);
        if (!animate) {
          springValue.jump(value);
          if (!settledRef.current) {
            settledRef.current = true;
            (_a2 = onSettledRef.current) == null ? void 0 : _a2.call(onSettledRef);
          }
        }
      };
      if (delay2 > 0) {
        const timer2 = setTimeout(run, delay2 * 1e3);
        return () => clearTimeout(timer2);
      }
      run();
    }, [motionValue2, springValue, delay2, value, animate]);
    reactExports.useEffect(
      () => springValue.on("change", (latest) => {
        var _a2;
        if (!ref.current) return;
        ref.current.textContent = formatTickerValue(
          latest,
          decimalPlaces,
          prefix,
          suffix
        );
        if (animate && !settledRef.current && Math.abs(latest - value) < 1 && Math.abs(springValue.getVelocity()) < 1) {
          settledRef.current = true;
          (_a2 = onSettledRef.current) == null ? void 0 : _a2.call(onSettledRef);
        }
      }),
      [springValue, decimalPlaces, prefix, suffix, animate, value]
    );
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "span",
      {
        ref,
        className: cn("inline-block tabular-nums", className),
        ...props,
        children: formatTickerValue(value, decimalPlaces, prefix, suffix)
      }
    );
  }
  const STORAGE_KEY_PREFIX$1 = "last_balance_";
  function storageKey$1(tornXid) {
    return `${STORAGE_KEY_PREFIX$1}${tornXid}`;
  }
  async function loadLastSeenBalance(tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        storageKey$1(tornXid)
      );
      if (typeof raw === "number" && Number.isFinite(raw)) return raw;
      return null;
    } catch {
      return null;
    }
  }
  async function saveLastSeenBalance(tornXid, balance) {
    if (!Number.isFinite(balance)) return;
    try {
      await getPlatformRuntime().storage.set(storageKey$1(tornXid), balance);
    } catch {
    }
  }
  var module$1 = {};
  (function main(global, module, isWorker, workerSize) {
    var canUseWorker = !!(global.Worker && global.Blob && global.Promise && global.OffscreenCanvas && global.OffscreenCanvasRenderingContext2D && global.HTMLCanvasElement && global.HTMLCanvasElement.prototype.transferControlToOffscreen && global.URL && global.URL.createObjectURL);
    var canUsePaths = typeof Path2D === "function" && typeof DOMMatrix === "function";
    var canDrawBitmap = (function() {
      if (!global.OffscreenCanvas) {
        return false;
      }
      try {
        var canvas = new OffscreenCanvas(1, 1);
        var ctx = canvas.getContext("2d");
        ctx.fillRect(0, 0, 1, 1);
        var bitmap = canvas.transferToImageBitmap();
        ctx.createPattern(bitmap, "no-repeat");
      } catch (e) {
        return false;
      }
      return true;
    })();
    function noop2() {
    }
    function promise(func) {
      var ModulePromise = module.exports.Promise;
      var Prom = ModulePromise !== void 0 ? ModulePromise : global.Promise;
      if (typeof Prom === "function") {
        return new Prom(func);
      }
      func(noop2, noop2);
      return null;
    }
    var bitmapMapper = /* @__PURE__ */ (function(skipTransform, map) {
      return {
        transform: function(bitmap) {
          if (skipTransform) {
            return bitmap;
          }
          if (map.has(bitmap)) {
            return map.get(bitmap);
          }
          var canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
          var ctx = canvas.getContext("2d");
          ctx.drawImage(bitmap, 0, 0);
          map.set(bitmap, canvas);
          return canvas;
        },
        clear: function() {
          map.clear();
        }
      };
    })(canDrawBitmap, /* @__PURE__ */ new Map());
    var raf = (function() {
      var TIME = Math.floor(1e3 / 60);
      var frame2, cancel2;
      var frames = {};
      var lastFrameTime = 0;
      if (typeof requestAnimationFrame === "function" && typeof cancelAnimationFrame === "function") {
        frame2 = function(cb) {
          var id2 = Math.random();
          frames[id2] = requestAnimationFrame(function onFrame(time2) {
            if (lastFrameTime === time2 || lastFrameTime + TIME - 1 < time2) {
              lastFrameTime = time2;
              delete frames[id2];
              cb();
            } else {
              frames[id2] = requestAnimationFrame(onFrame);
            }
          });
          return id2;
        };
        cancel2 = function(id2) {
          if (frames[id2]) {
            cancelAnimationFrame(frames[id2]);
          }
        };
      } else {
        frame2 = function(cb) {
          return setTimeout(cb, TIME);
        };
        cancel2 = function(timer2) {
          return clearTimeout(timer2);
        };
      }
      return { frame: frame2, cancel: cancel2 };
    })();
    var getWorker = /* @__PURE__ */ (function() {
      var worker;
      var prom;
      var resolves = {};
      function decorate(worker2) {
        function execute(options, callback) {
          worker2.postMessage({ options: options || {}, callback });
        }
        worker2.init = function initWorker(canvas) {
          var offscreen = canvas.transferControlToOffscreen();
          worker2.postMessage({ canvas: offscreen }, [offscreen]);
        };
        worker2.fire = function fireWorker(options, size, done) {
          if (prom) {
            execute(options, null);
            return prom;
          }
          var id2 = Math.random().toString(36).slice(2);
          prom = promise(function(resolve) {
            function workerDone(msg) {
              if (msg.data.callback !== id2) {
                return;
              }
              delete resolves[id2];
              worker2.removeEventListener("message", workerDone);
              prom = null;
              bitmapMapper.clear();
              done();
              resolve();
            }
            worker2.addEventListener("message", workerDone);
            execute(options, id2);
            resolves[id2] = workerDone.bind(null, { data: { callback: id2 } });
          });
          return prom;
        };
        worker2.reset = function resetWorker() {
          worker2.postMessage({ reset: true });
          for (var id2 in resolves) {
            resolves[id2]();
            delete resolves[id2];
          }
        };
      }
      return function() {
        if (worker) {
          return worker;
        }
        if (!isWorker && canUseWorker) {
          var code = [
            "var CONFETTI, SIZE = {}, module = {};",
            "(" + main.toString() + ")(this, module, true, SIZE);",
            "onmessage = function(msg) {",
            "  if (msg.data.options) {",
            "    CONFETTI(msg.data.options).then(function () {",
            "      if (msg.data.callback) {",
            "        postMessage({ callback: msg.data.callback });",
            "      }",
            "    });",
            "  } else if (msg.data.reset) {",
            "    CONFETTI && CONFETTI.reset();",
            "  } else if (msg.data.resize) {",
            "    SIZE.width = msg.data.resize.width;",
            "    SIZE.height = msg.data.resize.height;",
            "  } else if (msg.data.canvas) {",
            "    SIZE.width = msg.data.canvas.width;",
            "    SIZE.height = msg.data.canvas.height;",
            "    CONFETTI = module.exports.create(msg.data.canvas);",
            "  }",
            "}"
          ].join("\n");
          try {
            worker = new Worker(URL.createObjectURL(new Blob([code])));
          } catch (e) {
            typeof console !== "undefined" && typeof console.warn === "function" ? console.warn("🎊 Could not load worker", e) : null;
            return null;
          }
          decorate(worker);
        }
        return worker;
      };
    })();
    var defaults = {
      particleCount: 50,
      angle: 90,
      spread: 45,
      startVelocity: 45,
      decay: 0.9,
      gravity: 1,
      drift: 0,
      ticks: 200,
      x: 0.5,
      y: 0.5,
      shapes: ["square", "circle"],
      zIndex: 100,
      colors: [
        "#26ccff",
        "#a25afd",
        "#ff5e7e",
        "#88ff5a",
        "#fcff42",
        "#ffa62d",
        "#ff36ff"
      ],
      // probably should be true, but back-compat
      disableForReducedMotion: false,
      scalar: 1
    };
    function convert(val, transform2) {
      return transform2 ? transform2(val) : val;
    }
    function isOk(val) {
      return !(val === null || val === void 0);
    }
    function prop(options, name2, transform2) {
      return convert(
        options && isOk(options[name2]) ? options[name2] : defaults[name2],
        transform2
      );
    }
    function onlyPositiveInt(number2) {
      return number2 < 0 ? 0 : Math.floor(number2);
    }
    function randomInt(min, max) {
      return Math.floor(Math.random() * (max - min)) + min;
    }
    function toDecimal(str) {
      return parseInt(str, 16);
    }
    function colorsToRgb(colors) {
      return colors.map(hexToRgb);
    }
    function hexToRgb(str) {
      var val = String(str).replace(/[^0-9a-f]/gi, "");
      if (val.length < 6) {
        val = val[0] + val[0] + val[1] + val[1] + val[2] + val[2];
      }
      return {
        r: toDecimal(val.substring(0, 2)),
        g: toDecimal(val.substring(2, 4)),
        b: toDecimal(val.substring(4, 6))
      };
    }
    function getOrigin(options) {
      var origin = prop(options, "origin", Object);
      origin.x = prop(origin, "x", Number);
      origin.y = prop(origin, "y", Number);
      return origin;
    }
    function setCanvasWindowSize(canvas) {
      canvas.width = document.documentElement.clientWidth;
      canvas.height = document.documentElement.clientHeight;
    }
    function setCanvasRectSize(canvas) {
      var rect = canvas.getBoundingClientRect();
      canvas.width = rect.width;
      canvas.height = rect.height;
    }
    function getCanvas(zIndex) {
      var canvas = document.createElement("canvas");
      canvas.style.position = "fixed";
      canvas.style.top = "0px";
      canvas.style.left = "0px";
      canvas.style.pointerEvents = "none";
      canvas.style.zIndex = zIndex;
      return canvas;
    }
    function ellipse(context, x, y, radiusX, radiusY, rotation, startAngle, endAngle, antiClockwise) {
      context.save();
      context.translate(x, y);
      context.rotate(rotation);
      context.scale(radiusX, radiusY);
      context.arc(0, 0, 1, startAngle, endAngle, antiClockwise);
      context.restore();
    }
    function randomPhysics(opts) {
      var radAngle = opts.angle * (Math.PI / 180);
      var radSpread = opts.spread * (Math.PI / 180);
      return {
        x: opts.x,
        y: opts.y,
        wobble: Math.random() * 10,
        wobbleSpeed: Math.min(0.11, Math.random() * 0.1 + 0.05),
        velocity: opts.startVelocity * 0.5 + Math.random() * opts.startVelocity,
        angle2D: -radAngle + (0.5 * radSpread - Math.random() * radSpread),
        tiltAngle: (Math.random() * (0.75 - 0.25) + 0.25) * Math.PI,
        color: opts.color,
        shape: opts.shape,
        tick: 0,
        totalTicks: opts.ticks,
        decay: opts.decay,
        drift: opts.drift,
        random: Math.random() + 2,
        tiltSin: 0,
        tiltCos: 0,
        wobbleX: 0,
        wobbleY: 0,
        gravity: opts.gravity * 3,
        ovalScalar: 0.6,
        scalar: opts.scalar,
        flat: opts.flat
      };
    }
    function updateFetti(context, fetti) {
      fetti.x += Math.cos(fetti.angle2D) * fetti.velocity + fetti.drift;
      fetti.y += Math.sin(fetti.angle2D) * fetti.velocity + fetti.gravity;
      fetti.velocity *= fetti.decay;
      if (fetti.flat) {
        fetti.wobble = 0;
        fetti.wobbleX = fetti.x + 10 * fetti.scalar;
        fetti.wobbleY = fetti.y + 10 * fetti.scalar;
        fetti.tiltSin = 0;
        fetti.tiltCos = 0;
        fetti.random = 1;
      } else {
        fetti.wobble += fetti.wobbleSpeed;
        fetti.wobbleX = fetti.x + 10 * fetti.scalar * Math.cos(fetti.wobble);
        fetti.wobbleY = fetti.y + 10 * fetti.scalar * Math.sin(fetti.wobble);
        fetti.tiltAngle += 0.1;
        fetti.tiltSin = Math.sin(fetti.tiltAngle);
        fetti.tiltCos = Math.cos(fetti.tiltAngle);
        fetti.random = Math.random() + 2;
      }
      var progress2 = fetti.tick++ / fetti.totalTicks;
      var x1 = fetti.x + fetti.random * fetti.tiltCos;
      var y1 = fetti.y + fetti.random * fetti.tiltSin;
      var x2 = fetti.wobbleX + fetti.random * fetti.tiltCos;
      var y2 = fetti.wobbleY + fetti.random * fetti.tiltSin;
      context.fillStyle = "rgba(" + fetti.color.r + ", " + fetti.color.g + ", " + fetti.color.b + ", " + (1 - progress2) + ")";
      context.beginPath();
      if (canUsePaths && fetti.shape.type === "path" && typeof fetti.shape.path === "string" && Array.isArray(fetti.shape.matrix)) {
        context.fill(transformPath2D(
          fetti.shape.path,
          fetti.shape.matrix,
          fetti.x,
          fetti.y,
          Math.abs(x2 - x1) * 0.1,
          Math.abs(y2 - y1) * 0.1,
          Math.PI / 10 * fetti.wobble
        ));
      } else if (fetti.shape.type === "bitmap") {
        var rotation = Math.PI / 10 * fetti.wobble;
        var scaleX2 = Math.abs(x2 - x1) * 0.1;
        var scaleY2 = Math.abs(y2 - y1) * 0.1;
        var width = fetti.shape.bitmap.width * fetti.scalar;
        var height = fetti.shape.bitmap.height * fetti.scalar;
        var matrix = new DOMMatrix([
          Math.cos(rotation) * scaleX2,
          Math.sin(rotation) * scaleX2,
          -Math.sin(rotation) * scaleY2,
          Math.cos(rotation) * scaleY2,
          fetti.x,
          fetti.y
        ]);
        matrix.multiplySelf(new DOMMatrix(fetti.shape.matrix));
        var pattern = context.createPattern(bitmapMapper.transform(fetti.shape.bitmap), "no-repeat");
        pattern.setTransform(matrix);
        context.globalAlpha = 1 - progress2;
        context.fillStyle = pattern;
        context.fillRect(
          fetti.x - width / 2,
          fetti.y - height / 2,
          width,
          height
        );
        context.globalAlpha = 1;
      } else if (fetti.shape === "circle") {
        context.ellipse ? context.ellipse(fetti.x, fetti.y, Math.abs(x2 - x1) * fetti.ovalScalar, Math.abs(y2 - y1) * fetti.ovalScalar, Math.PI / 10 * fetti.wobble, 0, 2 * Math.PI) : ellipse(context, fetti.x, fetti.y, Math.abs(x2 - x1) * fetti.ovalScalar, Math.abs(y2 - y1) * fetti.ovalScalar, Math.PI / 10 * fetti.wobble, 0, 2 * Math.PI);
      } else if (fetti.shape === "star") {
        var rot = Math.PI / 2 * 3;
        var innerRadius = 4 * fetti.scalar;
        var outerRadius = 8 * fetti.scalar;
        var x = fetti.x;
        var y = fetti.y;
        var spikes = 5;
        var step2 = Math.PI / spikes;
        while (spikes--) {
          x = fetti.x + Math.cos(rot) * outerRadius;
          y = fetti.y + Math.sin(rot) * outerRadius;
          context.lineTo(x, y);
          rot += step2;
          x = fetti.x + Math.cos(rot) * innerRadius;
          y = fetti.y + Math.sin(rot) * innerRadius;
          context.lineTo(x, y);
          rot += step2;
        }
      } else {
        context.moveTo(Math.floor(fetti.x), Math.floor(fetti.y));
        context.lineTo(Math.floor(fetti.wobbleX), Math.floor(y1));
        context.lineTo(Math.floor(x2), Math.floor(y2));
        context.lineTo(Math.floor(x1), Math.floor(fetti.wobbleY));
      }
      context.closePath();
      context.fill();
      return fetti.tick < fetti.totalTicks;
    }
    function animate(canvas, fettis, resizer, size, done) {
      var animatingFettis = fettis.slice();
      var context = canvas.getContext("2d");
      var animationFrame;
      var destroy;
      var prom = promise(function(resolve) {
        function onDone() {
          animationFrame = destroy = null;
          context.clearRect(0, 0, size.width, size.height);
          bitmapMapper.clear();
          done();
          resolve();
        }
        function update() {
          if (isWorker && !(size.width === workerSize.width && size.height === workerSize.height)) {
            size.width = canvas.width = workerSize.width;
            size.height = canvas.height = workerSize.height;
          }
          if (!size.width && !size.height) {
            resizer(canvas);
            size.width = canvas.width;
            size.height = canvas.height;
          }
          context.clearRect(0, 0, size.width, size.height);
          animatingFettis = animatingFettis.filter(function(fetti) {
            return updateFetti(context, fetti);
          });
          if (animatingFettis.length) {
            animationFrame = raf.frame(update);
          } else {
            onDone();
          }
        }
        animationFrame = raf.frame(update);
        destroy = onDone;
      });
      return {
        addFettis: function(fettis2) {
          animatingFettis = animatingFettis.concat(fettis2);
          return prom;
        },
        canvas,
        promise: prom,
        reset: function() {
          if (animationFrame) {
            raf.cancel(animationFrame);
          }
          if (destroy) {
            destroy();
          }
        }
      };
    }
    function confettiCannon(canvas, globalOpts) {
      var isLibCanvas = !canvas;
      var allowResize = !!prop(globalOpts || {}, "resize");
      var hasResizeEventRegistered = false;
      var globalDisableForReducedMotion = prop(globalOpts, "disableForReducedMotion", Boolean);
      var shouldUseWorker = canUseWorker && !!prop(globalOpts || {}, "useWorker");
      var worker = shouldUseWorker ? getWorker() : null;
      var resizer = isLibCanvas ? setCanvasWindowSize : setCanvasRectSize;
      var initialized = canvas && worker ? !!canvas.__confetti_initialized : false;
      var preferLessMotion = typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion)").matches;
      var animationObj;
      function fireLocal(options, size, done) {
        var particleCount = prop(options, "particleCount", onlyPositiveInt);
        var angle = prop(options, "angle", Number);
        var spread = prop(options, "spread", Number);
        var startVelocity = prop(options, "startVelocity", Number);
        var decay = prop(options, "decay", Number);
        var gravity = prop(options, "gravity", Number);
        var drift = prop(options, "drift", Number);
        var colors = prop(options, "colors", colorsToRgb);
        var ticks = prop(options, "ticks", Number);
        var shapes = prop(options, "shapes");
        var scalar = prop(options, "scalar");
        var flat = !!prop(options, "flat");
        var origin = getOrigin(options);
        var temp = particleCount;
        var fettis = [];
        var startX = canvas.width * origin.x;
        var startY = canvas.height * origin.y;
        while (temp--) {
          fettis.push(
            randomPhysics({
              x: startX,
              y: startY,
              angle,
              spread,
              startVelocity,
              color: colors[temp % colors.length],
              shape: shapes[randomInt(0, shapes.length)],
              ticks,
              decay,
              gravity,
              drift,
              scalar,
              flat
            })
          );
        }
        if (animationObj) {
          return animationObj.addFettis(fettis);
        }
        animationObj = animate(canvas, fettis, resizer, size, done);
        return animationObj.promise;
      }
      function fire(options) {
        var disableForReducedMotion = globalDisableForReducedMotion || prop(options, "disableForReducedMotion", Boolean);
        var zIndex = prop(options, "zIndex", Number);
        if (disableForReducedMotion && preferLessMotion) {
          return promise(function(resolve) {
            resolve();
          });
        }
        if (isLibCanvas && animationObj) {
          canvas = animationObj.canvas;
        } else if (isLibCanvas && !canvas) {
          canvas = getCanvas(zIndex);
          document.body.appendChild(canvas);
        }
        if (allowResize && !initialized) {
          resizer(canvas);
        }
        var size = {
          width: canvas.width,
          height: canvas.height
        };
        if (worker && !initialized) {
          worker.init(canvas);
        }
        initialized = true;
        if (worker) {
          canvas.__confetti_initialized = true;
        }
        function onResize() {
          if (worker) {
            var obj = {
              getBoundingClientRect: function() {
                if (!isLibCanvas) {
                  return canvas.getBoundingClientRect();
                }
              }
            };
            resizer(obj);
            worker.postMessage({
              resize: {
                width: obj.width,
                height: obj.height
              }
            });
            return;
          }
          size.width = size.height = null;
        }
        function done() {
          animationObj = null;
          if (allowResize) {
            hasResizeEventRegistered = false;
            global.removeEventListener("resize", onResize);
          }
          if (isLibCanvas && canvas) {
            if (document.body.contains(canvas)) {
              document.body.removeChild(canvas);
            }
            canvas = null;
            initialized = false;
          }
        }
        if (allowResize && !hasResizeEventRegistered) {
          hasResizeEventRegistered = true;
          global.addEventListener("resize", onResize, false);
        }
        if (worker) {
          return worker.fire(options, size, done);
        }
        return fireLocal(options, size, done);
      }
      fire.reset = function() {
        if (worker) {
          worker.reset();
        }
        if (animationObj) {
          animationObj.reset();
        }
      };
      return fire;
    }
    var defaultFire;
    function getDefaultFire() {
      if (!defaultFire) {
        defaultFire = confettiCannon(null, { useWorker: true, resize: true });
      }
      return defaultFire;
    }
    function transformPath2D(pathString, pathMatrix, x, y, scaleX2, scaleY2, rotation) {
      var path2d = new Path2D(pathString);
      var t1 = new Path2D();
      t1.addPath(path2d, new DOMMatrix(pathMatrix));
      var t2 = new Path2D();
      t2.addPath(t1, new DOMMatrix([
        Math.cos(rotation) * scaleX2,
        Math.sin(rotation) * scaleX2,
        -Math.sin(rotation) * scaleY2,
        Math.cos(rotation) * scaleY2,
        x,
        y
      ]));
      return t2;
    }
    function shapeFromPath(pathData) {
      if (!canUsePaths) {
        throw new Error("path confetti are not supported in this browser");
      }
      var path, matrix;
      if (typeof pathData === "string") {
        path = pathData;
      } else {
        path = pathData.path;
        matrix = pathData.matrix;
      }
      var path2d = new Path2D(path);
      var tempCanvas = document.createElement("canvas");
      var tempCtx = tempCanvas.getContext("2d");
      if (!matrix) {
        var maxSize = 1e3;
        var minX = maxSize;
        var minY = maxSize;
        var maxX = 0;
        var maxY = 0;
        var width, height;
        for (var x = 0; x < maxSize; x += 2) {
          for (var y = 0; y < maxSize; y += 2) {
            if (tempCtx.isPointInPath(path2d, x, y, "nonzero")) {
              minX = Math.min(minX, x);
              minY = Math.min(minY, y);
              maxX = Math.max(maxX, x);
              maxY = Math.max(maxY, y);
            }
          }
        }
        width = maxX - minX;
        height = maxY - minY;
        var maxDesiredSize = 10;
        var scale2 = Math.min(maxDesiredSize / width, maxDesiredSize / height);
        matrix = [
          scale2,
          0,
          0,
          scale2,
          -Math.round(width / 2 + minX) * scale2,
          -Math.round(height / 2 + minY) * scale2
        ];
      }
      return {
        type: "path",
        path,
        matrix
      };
    }
    function shapeFromText(textData) {
      var text2, scalar = 1, color2 = "#000000", fontFamily = '"Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji", "EmojiOne Color", "Android Emoji", "Twemoji Mozilla", "system emoji", sans-serif';
      if (typeof textData === "string") {
        text2 = textData;
      } else {
        text2 = textData.text;
        scalar = "scalar" in textData ? textData.scalar : scalar;
        fontFamily = "fontFamily" in textData ? textData.fontFamily : fontFamily;
        color2 = "color" in textData ? textData.color : color2;
      }
      var fontSize = 10 * scalar;
      var font = "" + fontSize + "px " + fontFamily;
      var canvas = new OffscreenCanvas(fontSize, fontSize);
      var ctx = canvas.getContext("2d");
      ctx.font = font;
      var size = ctx.measureText(text2);
      var width = Math.ceil(size.actualBoundingBoxRight + size.actualBoundingBoxLeft);
      var height = Math.ceil(size.actualBoundingBoxAscent + size.actualBoundingBoxDescent);
      var padding = 2;
      var x = size.actualBoundingBoxLeft + padding;
      var y = size.actualBoundingBoxAscent + padding;
      width += padding + padding;
      height += padding + padding;
      canvas = new OffscreenCanvas(width, height);
      ctx = canvas.getContext("2d");
      ctx.font = font;
      ctx.fillStyle = color2;
      ctx.fillText(text2, x, y);
      var scale2 = 1 / scalar;
      return {
        type: "bitmap",
        // TODO these probably need to be transfered for workers
        bitmap: canvas.transferToImageBitmap(),
        matrix: [scale2, 0, 0, scale2, -width * scale2 / 2, -height * scale2 / 2]
      };
    }
    module.exports = function() {
      return getDefaultFire().apply(this, arguments);
    };
    module.exports.reset = function() {
      getDefaultFire().reset();
    };
    module.exports.create = confettiCannon;
    module.exports.shapeFromPath = shapeFromPath;
    module.exports.shapeFromText = shapeFromText;
  })((function() {
    if (typeof window !== "undefined") {
      return window;
    }
    if (typeof self !== "undefined") {
      return self;
    }
    return this || {};
  })(), module$1, false);
  const confetti = module$1.exports;
  module$1.exports.create;
  const CONFETTI_CANVAS_ID = "tlm-confetti-canvas";
  const CONFETTI_Z_INDEX = 2147483647;
  const BALANCE_CONFETTI_ANGLE = 225;
  const BALANCE_CONFETTI_SPREAD = 32;
  const BALANCE_CONFETTI_ORIGIN = { x: 1, y: 0 };
  let shadowConfetti = null;
  function getShadowConfetti() {
    const host = document.getElementById(CONTENT_HOST_ID) ?? document.getElementById(LEGACY_CONTENT_HOST_ID);
    const root2 = host == null ? void 0 : host.shadowRoot;
    if (!root2) return null;
    let canvas = root2.getElementById(CONFETTI_CANVAS_ID);
    if (!canvas) {
      canvas = document.createElement("canvas");
      canvas.id = CONFETTI_CANVAS_ID;
      canvas.style.position = "fixed";
      canvas.style.inset = "0";
      canvas.style.width = "100%";
      canvas.style.height = "100%";
      canvas.style.pointerEvents = "none";
      canvas.style.zIndex = String(CONFETTI_Z_INDEX);
      root2.appendChild(canvas);
    }
    if (!shadowConfetti) {
      shadowConfetti = confetti.create(canvas, { resize: true });
    }
    return shadowConfetti;
  }
  function fireBalanceConfetti() {
    const shoot = getShadowConfetti();
    if (!shoot) return;
    try {
      shoot({
        particleCount: 50,
        angle: BALANCE_CONFETTI_ANGLE,
        spread: BALANCE_CONFETTI_SPREAD,
        startVelocity: 22,
        ticks: 400,
        scalar: 0.4,
        origin: BALANCE_CONFETTI_ORIGIN
      });
    } catch {
    }
  }
  const BalanceButton = reactExports.forwardRef(
    function BalanceButton2({
      balance,
      panelOpen: panelOpen2,
      tornXid,
      balanceLoading = false,
      suppressConfetti = false,
      onClick,
      className
    }, ref) {
      const [displayed, setDisplayed] = reactExports.useState(null);
      const prevBalanceRef = reactExports.useRef(null);
      const lastConfettiBalanceRef = reactExports.useRef(null);
      const hydrationSeedRef = reactExports.useRef(null);
      const increaseBurstRef = reactExports.useRef(null);
      const prevPanelOpenRef = reactExports.useRef(panelOpen2);
      const balanceRef = reactExports.useRef(balance);
      balanceRef.current = balance;
      const [hydrated, setHydrated] = reactExports.useState(false);
      const lastXidRef = reactExports.useRef(tornXid);
      reactExports.useEffect(() => {
        if (lastXidRef.current === tornXid) return;
        lastXidRef.current = tornXid;
        setHydrated(false);
        setDisplayed(null);
        prevBalanceRef.current = null;
        lastConfettiBalanceRef.current = null;
        increaseBurstRef.current = null;
        hydrationSeedRef.current = null;
        prevPanelOpenRef.current = panelOpen2;
      }, [tornXid]);
      reactExports.useEffect(() => {
        if (balanceLoading) return;
        if (hydrated) return;
        let cancelled = false;
        void (async () => {
          const stored = tornXid !== null ? await loadLastSeenBalance(tornXid) : null;
          if (cancelled) return;
          const seed = stored ?? balanceRef.current;
          setDisplayed(seed);
          prevBalanceRef.current = seed;
          lastConfettiBalanceRef.current = seed;
          hydrationSeedRef.current = seed;
          setHydrated(true);
          if (tornXid !== null && stored === null) {
            void saveLastSeenBalance(tornXid, balanceRef.current);
          }
        })();
        return () => {
          cancelled = true;
        };
      }, [tornXid, balanceLoading, hydrated]);
      reactExports.useEffect(() => {
        if (!hydrated) return;
        if (!panelOpen2) return;
        setDisplayed(balance);
      }, [hydrated, panelOpen2, balance]);
      reactExports.useEffect(() => {
        if (!hydrated) return;
        if (!panelOpen2) return;
        if (tornXid === null) return;
        void saveLastSeenBalance(tornXid, balance);
      }, [hydrated, panelOpen2, balance, tornXid]);
      reactExports.useEffect(() => {
        if (!hydrated) return;
        const wasOpen = prevPanelOpenRef.current;
        prevPanelOpenRef.current = panelOpen2;
        if (!panelOpen2) {
          prevBalanceRef.current = balance;
          lastConfettiBalanceRef.current = balance;
          increaseBurstRef.current = null;
          return;
        }
        if (!wasOpen) {
          prevBalanceRef.current = balance;
          lastConfettiBalanceRef.current = balance;
          increaseBurstRef.current = null;
          return;
        }
        const prev = prevBalanceRef.current;
        prevBalanceRef.current = balance;
        if (suppressConfetti) return;
        const hydrationSeed = hydrationSeedRef.current;
        if (hydrationSeed !== null) {
          hydrationSeedRef.current = null;
          if (hydrationSeed === 0 && balance > 0) {
            prevBalanceRef.current = balance;
            lastConfettiBalanceRef.current = balance;
            increaseBurstRef.current = null;
            return;
          }
        }
        if (prev === null) {
          lastConfettiBalanceRef.current = balance;
          return;
        }
        if (balance < prev) {
          lastConfettiBalanceRef.current = balance;
          increaseBurstRef.current = null;
          return;
        }
        if (balance <= prev) return;
        if (increaseBurstRef.current === null) {
          fireBalanceConfetti();
          increaseBurstRef.current = prev;
        }
        lastConfettiBalanceRef.current = balance;
      }, [balance, panelOpen2, suppressConfetti, hydrated]);
      const internalButtonRef = reactExports.useRef(null);
      const setButtonRef = (node) => {
        internalButtonRef.current = node;
        if (typeof ref === "function") ref(node);
        else if (ref) {
          ref.current = node;
        }
      };
      const [xanaxTier, setXanaxTier] = reactExports.useState(0);
      const [measureNonce, setMeasureNonce] = reactExports.useState(0);
      const getHeaderRow = () => {
        var _a2, _b;
        return ((_b = (_a2 = internalButtonRef.current) == null ? void 0 : _a2.parentElement) == null ? void 0 : _b.parentElement) ?? null;
      };
      reactExports.useLayoutEffect(() => {
        setXanaxTier(0);
        setMeasureNonce((n) => n + 1);
      }, [balance]);
      reactExports.useLayoutEffect(() => {
        const row2 = getHeaderRow();
        if (!row2 || typeof ResizeObserver === "undefined") return;
        const observer2 = new ResizeObserver(() => {
          setXanaxTier(0);
          setMeasureNonce((n) => n + 1);
        });
        observer2.observe(row2);
        return () => observer2.disconnect();
      }, []);
      reactExports.useLayoutEffect(() => {
        const row2 = getHeaderRow();
        if (!row2) return;
        if (xanaxTier < 2 && row2.scrollWidth > row2.clientWidth + 1) {
          setXanaxTier((t) => Math.min(t + 1, 2));
        }
      }, [xanaxTier, measureNonce]);
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          ref: setButtonRef,
          className,
          onClick,
          "aria-label": "Open wallet — deposit or withdraw",
          children: [
            displayed === null ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: `${(balance ?? 0).toLocaleString("en-US")} PTS` }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
              NumberTicker,
              {
                value: displayed,
                animate: panelOpen2,
                suffix: " PTS"
              }
            ),
            balance > 0 && xanaxTier < 2 && /* @__PURE__ */ jsxRuntimeExports.jsx(
              "span",
              {
                style: {
                  marginLeft: 5,
                  opacity: 0.6,
                  fontWeight: 500,
                  display: "inline-flex",
                  alignItems: "center",
                  gap: 3,
                  whiteSpace: "nowrap"
                },
                children: xanaxTier === 0 ? `(${formatXanaxAmount(balance)} Xanax)` : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                  `(${formatXanaxAmount(balance)} `,
                  /* @__PURE__ */ jsxRuntimeExports.jsx(Pill, { size: 13, "aria-label": "Xanax" }),
                  ")"
                ] })
              }
            )
          ]
        }
      );
    }
  );
  BalanceButton.displayName = "BalanceButton";
  const PANEL_LOCK_MESSAGES = {
    sell: "Complete your active loss contract before starting another.",
    redeem: "Complete your existing withdrawal contract.",
    bounty: "Complete your active bounty contract before starting another.",
    service: "Complete your active contract before starting another."
  };
  function getActiveFulfillmentKind(contractActive, redeemingContractActive, bountyContractActive = false, serviceContractActive = false) {
    if (contractActive) return "sell";
    if (redeemingContractActive) return "redeem";
    if (bountyContractActive) return "bounty";
    if (serviceContractActive) return "service";
    return null;
  }
  function isPanelLockedByActiveFulfillment(panel2, kind) {
    if (!kind) return false;
    if (kind === "sell") return panel2 !== "buying";
    if (kind === "redeem" || kind === "bounty" || kind === "service") {
      return panel2 !== "redeeming";
    }
    return false;
  }
  function getPanelLockMessage(panel2, kind) {
    if (!kind || !isPanelLockedByActiveFulfillment(panel2, kind)) return "";
    return PANEL_LOCK_MESSAGES[kind];
  }
  const STORAGE_KEY_PREFIX = "buyers_panel_sections_";
  const DEFAULT_BUYERS_PANEL_SECTIONS_EXPANDED = {
    yourContracts: true,
    buy: true,
    services: true
  };
  function storageKey(tornXid) {
    return tornXid == null ? `${STORAGE_KEY_PREFIX}guest` : `${STORAGE_KEY_PREFIX}${tornXid}`;
  }
  function syncKey$2(tornXid) {
    return storageKey(tornXid);
  }
  function isSectionsExpanded(value) {
    if (value == null || typeof value !== "object") return false;
    const o = value;
    return typeof o.yourContracts === "boolean" && typeof o.buy === "boolean" && typeof o.services === "boolean";
  }
  function migrateLegacySections(raw) {
    if (typeof raw.yourContracts !== "boolean" || typeof raw.buy !== "boolean") {
      return null;
    }
    const services = typeof raw.services === "boolean" ? raw.services : typeof raw.insurance === "boolean" ? raw.insurance : null;
    if (services === null) return null;
    return {
      yourContracts: raw.yourContracts,
      buy: raw.buy,
      services
    };
  }
  function parseSections(raw) {
    if (typeof raw === "string") {
      try {
        return parseSections(JSON.parse(raw));
      } catch {
        return null;
      }
    }
    if (isSectionsExpanded(raw)) return raw;
    if (raw != null && typeof raw === "object") {
      return migrateLegacySections(raw);
    }
    return null;
  }
  function readSync$3(tornXid) {
    try {
      const raw = readLocalStorageWithMigration(localStorage, syncKey$2(tornXid));
      if (raw == null) return null;
      return parseSections(raw);
    } catch {
      return null;
    }
  }
  function writeSync$3(tornXid, sections) {
    try {
      writeLocalStorageCurrent(
        localStorage,
        syncKey$2(tornXid),
        JSON.stringify(sections)
      );
    } catch {
    }
  }
  function readStoredBuyersPanelSectionsSync(tornXid) {
    return readSync$3(tornXid) ?? DEFAULT_BUYERS_PANEL_SECTIONS_EXPANDED;
  }
  async function loadBuyersPanelSections(tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(storageKey(tornXid));
      const parsed = parseSections(raw);
      if (parsed != null) {
        writeSync$3(tornXid, parsed);
        return parsed;
      }
    } catch {
    }
    return readSync$3(tornXid) ?? DEFAULT_BUYERS_PANEL_SECTIONS_EXPANDED;
  }
  async function saveBuyersPanelSections(tornXid, sections) {
    writeSync$3(tornXid, sections);
    try {
      await getPlatformRuntime().storage.set(storageKey(tornXid), sections);
    } catch {
    }
  }
  const BUY_KEY_PREFIX = "contract_type_buy_";
  const SELL_KEY_PREFIX = "contract_type_sell_";
  function buyKey(tornXid) {
    return tornXid == null ? `${BUY_KEY_PREFIX}guest` : `${BUY_KEY_PREFIX}${tornXid}`;
  }
  function sellKey(tornXid) {
    return tornXid == null ? `${SELL_KEY_PREFIX}guest` : `${SELL_KEY_PREFIX}${tornXid}`;
  }
  function syncKey$1(scope, tornXid) {
    const prefix = scope === "buy" ? BUY_KEY_PREFIX : SELL_KEY_PREFIX;
    return tornXid == null ? `${prefix}guest` : `${prefix}${tornXid}`;
  }
  function readSync$2(scope, tornXid) {
    try {
      const raw = readLocalStorageWithMigration(
        localStorage,
        syncKey$1(scope, tornXid)
      );
      if (typeof raw === "string" && isContractType(raw)) return raw;
    } catch {
    }
    return null;
  }
  function writeSync$2(scope, tornXid, type) {
    try {
      writeLocalStorageCurrent(localStorage, syncKey$1(scope, tornXid), type);
    } catch {
    }
  }
  function readStoredBuyContractTypeSync(tornXid) {
    return readSync$2("buy", tornXid);
  }
  function readStoredSellContractTypeSync(tornXid) {
    return readSync$2("sell", tornXid);
  }
  async function loadContractType(scope, tornXid, fallback) {
    const key = scope === "buy" ? buyKey(tornXid) : sellKey(tornXid);
    try {
      const raw = await getPlatformRuntime().storage.get(key);
      if (typeof raw === "string" && isContractType(raw)) {
        writeSync$2(scope, tornXid, raw);
        return raw;
      }
    } catch {
    }
    const cached = readSync$2(scope, tornXid);
    if (cached != null) return cached;
    return fallback;
  }
  async function saveContractType(scope, tornXid, type) {
    writeSync$2(scope, tornXid, type);
    const key = scope === "buy" ? buyKey(tornXid) : sellKey(tornXid);
    try {
      await getPlatformRuntime().storage.set(key, type);
    } catch {
    }
  }
  async function loadBuyContractType(tornXid) {
    return loadContractType("buy", tornXid, "losses");
  }
  async function saveBuyContractType(tornXid, type) {
    return saveContractType("buy", tornXid, type);
  }
  async function loadSellContractType(tornXid) {
    return loadContractType("sell", tornXid, "losses");
  }
  async function saveSellContractType(tornXid, type) {
    return saveContractType("sell", tornXid, type);
  }
  function ContractTypeIcon({
    type,
    size = 14,
    className,
    strokeWidth = 2
  }) {
    const props = {
      size,
      className,
      strokeWidth,
      "aria-hidden": true
    };
    switch (type) {
      case "losses":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Skull, { ...props });
      case "escapes":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Wind, { ...props });
      case "stalemates":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Shield, { ...props });
    }
  }
  const inlineWrap = "_inlineWrap_1fno3_2";
  const inlineTrigger = "_inlineTrigger_1fno3_8";
  const inlineTriggerLabel = "_inlineTriggerLabel_1fno3_53";
  const inlineChevron = "_inlineChevron_1fno3_58";
  const inlineMenu = "_inlineMenu_1fno3_69";
  const inlineMenuItem = "_inlineMenuItem_1fno3_84";
  const inlineOption = "_inlineOption_1fno3_90";
  const inlineOptionIcon = "_inlineOptionIcon_1fno3_115";
  const segment$1 = "_segment_1fno3_144";
  const segmentPill = "_segmentPill_1fno3_159";
  const segmentPillAlert = "_segmentPillAlert_1fno3_192";
  const segmentPillHidden = "_segmentPillHidden_1fno3_204";
  const segmentPillInstant = "_segmentPillInstant_1fno3_208";
  const segmentButton = "_segmentButton_1fno3_212";
  const segmentButtonIcon = "_segmentButtonIcon_1fno3_236";
  const segmentButtonAlert = "_segmentButtonAlert_1fno3_268";
  const segmentOtherWrap = "_segmentOtherWrap_1fno3_285";
  const segmentOtherMenu = "_segmentOtherMenu_1fno3_297";
  const segmentOtherMenuItem = "_segmentOtherMenuItem_1fno3_312";
  const segmentOtherOption = "_segmentOtherOption_1fno3_318";
  const segmentOtherOptionIcon = "_segmentOtherOptionIcon_1fno3_343";
  const segmentOtherOptionEmbargo = "_segmentOtherOptionEmbargo_1fno3_363";
  const segmentOtherOptionGray = "_segmentOtherOptionGray_1fno3_379";
  const segmentOtherOptionAlert = "_segmentOtherOptionAlert_1fno3_397";
  const segmentOtherChevron = "_segmentOtherChevron_1fno3_416";
  const segmentButtonOtherOpen = "_segmentButtonOtherOpen_1fno3_423";
  const styles$g = {
    inlineWrap,
    inlineTrigger,
    inlineTriggerLabel,
    inlineChevron,
    inlineMenu,
    inlineMenuItem,
    inlineOption,
    inlineOptionIcon,
    segment: segment$1,
    segmentPill,
    segmentPillAlert,
    segmentPillHidden,
    segmentPillInstant,
    segmentButton,
    segmentButtonIcon,
    segmentButtonAlert,
    segmentOtherWrap,
    segmentOtherMenu,
    segmentOtherMenuItem,
    segmentOtherOption,
    segmentOtherOptionIcon,
    segmentOtherOptionEmbargo,
    segmentOtherOptionGray,
    segmentOtherOptionAlert,
    segmentOtherChevron,
    segmentButtonOtherOpen
  };
  function ContractTypePicker({
    variant,
    value,
    onChange,
    id: id2,
    disabled = false,
    alertHighlightedTypes,
    "aria-label": ariaLabel = "Contract type"
  }) {
    const menuId = reactExports.useId();
    const wrapRef = reactExports.useRef(null);
    const tablistRef = reactExports.useRef(null);
    const userInitiatedChangeRef = reactExports.useRef(false);
    const segmentMountedRef = reactExports.useRef(false);
    const [menuOpen, setMenuOpen] = reactExports.useState(false);
    const [segmentPillVisible, setSegmentPillVisible] = reactExports.useState(false);
    const [segmentPillAnimates, setSegmentPillAnimates] = reactExports.useState(false);
    const activeIndex = CONTRACT_TYPES.indexOf(value);
    const pillAlert2 = (alertHighlightedTypes == null ? void 0 : alertHighlightedTypes.has(value)) === true;
    reactExports.useLayoutEffect(() => {
      if (variant !== "segment") return;
      if (userInitiatedChangeRef.current) {
        userInitiatedChangeRef.current = false;
        setSegmentPillVisible(true);
        return;
      }
      if (!segmentMountedRef.current) {
        segmentMountedRef.current = true;
        setSegmentPillVisible(true);
        setSegmentPillAnimates(false);
        let animateFrame2 = 0;
        const showFrame2 = requestAnimationFrame(() => {
          animateFrame2 = requestAnimationFrame(() => {
            setSegmentPillAnimates(true);
          });
        });
        return () => {
          cancelAnimationFrame(showFrame2);
          cancelAnimationFrame(animateFrame2);
        };
      }
      setSegmentPillVisible(false);
      setSegmentPillAnimates(false);
      let showFrame = 0;
      let animateFrame = 0;
      const hideFrame = requestAnimationFrame(() => {
        showFrame = requestAnimationFrame(() => {
          setSegmentPillVisible(true);
          animateFrame = requestAnimationFrame(() => {
            setSegmentPillAnimates(true);
          });
        });
      });
      return () => {
        cancelAnimationFrame(hideFrame);
        cancelAnimationFrame(showFrame);
        cancelAnimationFrame(animateFrame);
      };
    }, [variant, value]);
    reactExports.useEffect(() => {
      if (!menuOpen) return;
      const handlePointerDown = (event) => {
        const path = event.composedPath();
        if (!path.includes(wrapRef.current)) {
          setMenuOpen(false);
        }
      };
      document.addEventListener("mousedown", handlePointerDown);
      return () => document.removeEventListener("mousedown", handlePointerDown);
    }, [menuOpen]);
    const handleSegmentKeyDown = reactExports.useCallback(
      (e, index) => {
        var _a2, _b;
        let nextIndex = index;
        if (e.key === "ArrowRight" || e.key === "ArrowDown") {
          e.preventDefault();
          nextIndex = (index + 1) % CONTRACT_TYPES.length;
        } else if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
          e.preventDefault();
          nextIndex = (index - 1 + CONTRACT_TYPES.length) % CONTRACT_TYPES.length;
        } else if (e.key === "Home") {
          e.preventDefault();
          nextIndex = 0;
        } else if (e.key === "End") {
          e.preventDefault();
          nextIndex = CONTRACT_TYPES.length - 1;
        } else {
          return;
        }
        userInitiatedChangeRef.current = true;
        onChange(CONTRACT_TYPES[nextIndex]);
        const tabs2 = (_a2 = tablistRef.current) == null ? void 0 : _a2.querySelectorAll(
          '[role="tab"]'
        );
        (_b = tabs2 == null ? void 0 : tabs2[nextIndex]) == null ? void 0 : _b.focus();
      },
      [onChange]
    );
    const selectType = (type) => {
      onChange(type);
      setMenuOpen(false);
    };
    if (variant === "inline") {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$g.inlineWrap, ref: wrapRef, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "button",
          {
            id: id2,
            type: "button",
            className: styles$g.inlineTrigger,
            disabled,
            "aria-label": ariaLabel,
            "aria-haspopup": "listbox",
            "aria-expanded": menuOpen,
            "aria-controls": menuId,
            onClick: () => setMenuOpen((open) => !open),
            onKeyDown: (e) => {
              if (e.key === "Escape") {
                e.preventDefault();
                setMenuOpen(false);
              }
              if (e.key === "ArrowDown" && !menuOpen) {
                e.preventDefault();
                setMenuOpen(true);
              }
            },
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$g.inlineTriggerLabel, children: CONTRACT_TYPE_LABELS[value] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronIcon$2, { className: styles$g.inlineChevron })
            ]
          }
        ),
        menuOpen && /* @__PURE__ */ jsxRuntimeExports.jsx(
          "ul",
          {
            id: menuId,
            className: styles$g.inlineMenu,
            role: "listbox",
            "aria-label": ariaLabel,
            children: CONTRACT_TYPES.map((type) => {
              const selected = type === value;
              return /* @__PURE__ */ jsxRuntimeExports.jsx("li", { className: styles$g.inlineMenuItem, role: "presentation", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "button",
                {
                  type: "button",
                  role: "option",
                  "aria-selected": selected,
                  className: styles$g.inlineOption,
                  onClick: () => selectType(type),
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      ContractTypeIcon,
                      {
                        type,
                        size: 15,
                        className: styles$g.inlineOptionIcon
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: CONTRACT_TYPE_LABELS[type] })
                  ]
                }
              ) }, type);
            })
          }
        )
      ] });
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        ref: tablistRef,
        className: styles$g.segment,
        role: "tablist",
        "aria-label": ariaLabel,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: `${styles$g.segmentPill} ${segmentPillVisible ? "" : styles$g.segmentPillHidden} ${segmentPillAnimates ? "" : styles$g.segmentPillInstant} ${pillAlert2 ? styles$g.segmentPillAlert : ""}`,
              style: { transform: `translateX(${activeIndex * 100}%)` },
              "aria-hidden": "true"
            }
          ),
          CONTRACT_TYPES.map((type, index) => {
            const selected = type === value;
            const alertHighlighted = (alertHighlightedTypes == null ? void 0 : alertHighlightedTypes.has(type)) === true;
            return /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "button",
              {
                type: "button",
                role: "tab",
                "aria-selected": selected,
                tabIndex: selected ? 0 : -1,
                className: `${styles$g.segmentButton} ${alertHighlighted ? styles$g.segmentButtonAlert : ""}`,
                disabled,
                onClick: () => {
                  userInitiatedChangeRef.current = true;
                  onChange(type);
                },
                onKeyDown: (e) => handleSegmentKeyDown(e, index),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    ContractTypeIcon,
                    {
                      type,
                      size: 14,
                      className: styles$g.segmentButtonIcon
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: CONTRACT_TYPE_LABELS[type] })
                ]
              },
              type
            );
          })
        ]
      }
    );
  }
  function ChevronIcon$2({ className }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "svg",
      {
        className,
        width: "10",
        height: "10",
        viewBox: "0 0 24 24",
        fill: "none",
        "aria-hidden": true,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "path",
          {
            d: "M6 9l6 6 6-6",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
          }
        )
      }
    );
  }
  const card$2 = "_card_19t6u_1";
  const badge$3 = "_badge_19t6u_22";
  const badgeRow = "_badgeRow_19t6u_27";
  const fileClaimButton = "_fileClaimButton_19t6u_35";
  const autoRenewPill = "_autoRenewPill_19t6u_82";
  const payoutValue$1 = "_payoutValue_19t6u_120";
  const timeLeft = "_timeLeft_19t6u_124";
  const styles$f = {
    card: card$2,
    badge: badge$3,
    badgeRow,
    fileClaimButton,
    autoRenewPill,
    payoutValue: payoutValue$1,
    timeLeft
  };
  function ActiveInsuranceCard({
    policy,
    onFileClaim,
    onExpired,
    onDisableAutoRenew,
    payoutConversion
  }) {
    const [autoRenewBusy, setAutoRenewBusy] = reactExports.useState(false);
    const [autoRenew, setAutoRenew] = reactExports.useState(policy.autoRenew);
    reactExports.useEffect(() => {
      setAutoRenew(policy.autoRenew);
    }, [policy.autoRenew, policy.id]);
    const handleExpired = reactExports.useCallback(() => {
      onExpired(policy.id);
    }, [onExpired, policy.id]);
    const secondsRemaining = useContractCountdown(policy.endsAt, handleExpired);
    const planLabel = INSURANCE_PLAN_LABELS[policy.planId];
    const openClaim = reactExports.useCallback(() => {
      onFileClaim(policy);
    }, [onFileClaim, policy]);
    const handleDisableAutoRenew = reactExports.useCallback(
      async (e) => {
        e.stopPropagation();
        if (!autoRenew || autoRenewBusy) return;
        setAutoRenewBusy(true);
        try {
          await onDisableAutoRenew(policy.id);
          setAutoRenew(false);
        } finally {
          setAutoRenewBusy(false);
        }
      },
      [autoRenew, autoRenewBusy, onDisableAutoRenew, policy.id]
    );
    const handleKeyDown = (e) => {
      if (e.key === "Enter" || e.key === " ") {
        e.preventDefault();
        openClaim();
      }
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "article",
      {
        className: `${styles$n.openCard} ${styles$f.card}`,
        role: "button",
        tabIndex: 0,
        "aria-label": `${planLabel} insurance policy — file claim`,
        onClick: openClaim,
        onKeyDown: handleKeyDown,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: styles$f.fileClaimButton,
              onClick: (e) => {
                e.stopPropagation();
                openClaim();
              },
              children: "File Claim"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$f.badgeRow, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: `${styles$n.openCardBadge} ${styles$f.badge}`, children: [
              "Insurance — ",
              planLabel
            ] }),
            autoRenew && /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                type: "button",
                className: styles$f.autoRenewPill,
                disabled: autoRenewBusy,
                "aria-label": "Turn off auto-renew",
                title: "Click to turn off auto-renew",
                onClick: (e) => void handleDisableAutoRenew(e),
                children: "Auto"
              }
            )
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRows, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRow, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Max payout" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "span",
                {
                  className: `${styles$n.openCardValue} ${styles$f.payoutValue} tlm-payout-hover-scope`,
                  onClick: (e) => e.stopPropagation(),
                  onKeyDown: (e) => e.stopPropagation(),
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    PayoutValue,
                    {
                      amount: policy.payout,
                      conversion: payoutConversion,
                      label: "Insurance max payout",
                      className: styles$f.payoutValue
                    }
                  )
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRow, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Time left" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$n.openCardValue} ${styles$f.timeLeft}`, children: formatInsuranceCountdown(secondsRemaining) })
            ] })
          ] })
        ]
      }
    );
  }
  function ActiveBountyOrderCard({
    order,
    onCancel,
    onShowInProgressView,
    payoutConversion
  }) {
    const inProgress = order.activeContracts.length > 0;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "article",
      {
        className: `${styles$n.openCard} ${styles$n.openCardOwn} ${styles$p.card}`,
        children: [
          inProgress ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "button",
            {
              type: "button",
              className: styles$n.inProgressBadge,
              "aria-label": "View in-progress bounty fulfillments",
              onClick: (e) => {
                e.stopPropagation();
                onShowInProgressView({
                  title: "Bounty contract — in progress",
                  subtitle: "Cancellation is locked while another user is placing bounties for this order.",
                  quantityLabel: "Bounties claimed",
                  parties: order.activeContracts
                });
              },
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.inProgressDot, "aria-hidden": "true" }),
                "In progress"
              ]
            }
          ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: styles$n.cancelOrder,
              "aria-label": "Cancel bounty order",
              onClick: (e) => {
                e.stopPropagation();
                onCancel(order);
              },
              children: "×"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$n.openCardBadge} ${styles$p.badge}`, children: "Bounties — open" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRows, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRow, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Quantity" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$n.openCardValue, children: [
                bountyOrderUncompletedQuantity(order).toLocaleString("en-US"),
                "/",
                order.quantity.toLocaleString("en-US")
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRow, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Target(s)" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(BountyTargetLinks, { targetIds: order.targetIds }) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$n.openCardRow} tlm-payout-hover-scope`, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Escrowed" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$n.openCardValue, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  PayoutValue,
                  {
                    amount: order.escrowedTotal * (order.quantityRemaining / order.quantity),
                    conversion: payoutConversion,
                    label: "Bounty order escrowed payout remaining",
                    className: styles$p.payoutValue
                  }
                ),
                " / ",
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  PayoutValue,
                  {
                    amount: order.escrowedTotal,
                    conversion: payoutConversion,
                    label: "Bounty order escrowed payout total",
                    className: styles$p.payoutValue
                  }
                )
              ] })
            ] })
          ] })
        ]
      },
      order.id
    );
  }
  const badge$2 = "_badge_igz09_1";
  const payoutValue = "_payoutValue_igz09_6";
  const valueGreen = "_valueGreen_igz09_10";
  const valueRed = "_valueRed_igz09_14";
  const valueGray = "_valueGray_igz09_18";
  const styles$e = {
    badge: badge$2,
    payoutValue,
    valueGreen,
    valueRed,
    valueGray
  };
  function ActiveProductivityBoostCard({
    boost,
    onCancel,
    payoutConversion
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "article",
      {
        className: `${styles$n.openCard} ${styles$n.openCardWithdraw}`,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: styles$n.cancelOrder,
              "aria-label": "Cancel productivity boost order",
              onClick: (e) => {
                e.stopPropagation();
                onCancel(boost);
              },
              children: "×"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              className: `${styles$n.openCardBadge} ${styles$n.openCardBadgeGreen} ${styles$e.badge}`,
              children: "Productivity Boost — open"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRows, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRow, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Company" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(ProductivityBoostCompanyLink, { companyId: boost.companyId }) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$n.openCardRow} tlm-payout-hover-scope`, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Escrowed" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$n.openCardValue} ${styles$e.valueGreen}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                PayoutValue,
                {
                  amount: boost.escrowedPts,
                  conversion: payoutConversion,
                  label: "Productivity boost escrowed payout",
                  className: styles$e.payoutValue
                }
              ) })
            ] })
          ] })
        ]
      }
    );
  }
  function ActiveEmbargoCard({
    embargo,
    onCancel,
    onShowInProgressView,
    payoutConversion
  }) {
    const inProgress = embargo.inProgress === true;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "article",
      {
        className: `${styles$n.openCard} ${styles$n.openCardEmbargo}`,
        children: [
          inProgress ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "button",
            {
              type: "button",
              className: styles$n.inProgressBadge,
              "aria-label": "View in-progress embargo fulfillment",
              onClick: (e) => {
                e.stopPropagation();
                onShowInProgressView({
                  title: "Embargo — in progress",
                  subtitle: "Cancellation is locked while another user is embargoing this target.",
                  quantityLabel: "Embargo",
                  parties: embargo.contractId && embargo.fulfillerXid != null ? [
                    {
                      id: embargo.contractId,
                      partyId: embargo.fulfillerXid,
                      quantity: 1,
                      endsAt: embargo.endsAt ?? 0
                    }
                  ] : []
                });
              },
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.inProgressDot, "aria-hidden": "true" }),
                "In progress"
              ]
            }
          ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: styles$n.cancelOrder,
              "aria-label": "Cancel embargo order",
              onClick: (e) => {
                e.stopPropagation();
                onCancel(embargo);
              },
              children: "×"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              className: `${styles$n.openCardBadge} ${styles$n.openCardBadgeRed}`,
              children: "Embargo — open"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRows, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRow, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Target" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(EmbargoTargetLink, { targetUserId: embargo.targetUserId }) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$n.openCardRow} tlm-payout-hover-scope`, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Escrowed" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$n.openCardValue} ${styles$e.valueRed}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                PayoutValue,
                {
                  amount: embargo.escrowedPts,
                  conversion: payoutConversion,
                  label: "Embargo escrowed payout",
                  className: styles$e.payoutValue
                }
              ) })
            ] })
          ] })
        ]
      }
    );
  }
  function ActiveReferencesCard({
    order,
    onCancel,
    onShowInProgressView,
    onViewReport,
    payoutConversion
  }) {
    const delivered = order.report != null;
    const inProgress = !delivered && order.inProgress === true;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "article",
      {
        className: `${styles$n.openCard} ${styles$n.openCardSimpleService}`,
        children: [
          delivered ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: styles$n.inProgressBadge,
              "aria-label": "View delivered references report",
              onClick: (e) => {
                e.stopPropagation();
                onViewReport(order);
              },
              children: "View report"
            }
          ) : inProgress ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "button",
            {
              type: "button",
              className: styles$n.inProgressBadge,
              "aria-label": "View in-progress references fulfillment",
              onClick: (e) => {
                e.stopPropagation();
                onShowInProgressView({
                  title: "References — in progress",
                  subtitle: "Cancellation is locked while another user is pulling references for this target.",
                  quantityLabel: "References",
                  parties: order.contractId && order.fulfillerXid != null ? [
                    {
                      id: order.contractId,
                      partyId: order.fulfillerXid,
                      quantity: 1,
                      endsAt: order.endsAt ?? 0
                    }
                  ] : []
                });
              },
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.inProgressDot, "aria-hidden": "true" }),
                "In progress"
              ]
            }
          ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: styles$n.cancelOrder,
              "aria-label": "Cancel references order",
              onClick: (e) => {
                e.stopPropagation();
                onCancel(order);
              },
              children: "×"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              className: `${styles$n.openCardBadge} ${styles$n.openCardBadgeGray}`,
              children: delivered ? "References — delivered" : "References — open"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRows, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRow, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Target" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(SimpleServiceTargetLink, { targetUserId: order.targetUserId }) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$n.openCardRow} tlm-payout-hover-scope`, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: delivered ? "Paid" : "Escrowed" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$n.openCardValue} ${styles$e.valueGray}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                PayoutValue,
                {
                  amount: order.escrowedPts,
                  conversion: payoutConversion,
                  label: "References escrowed payout",
                  className: styles$e.payoutValue
                }
              ) })
            ] })
          ] })
        ]
      }
    );
  }
  function ActiveBountyRevealCard({
    order,
    onCancel,
    onShowInProgressView,
    onViewReport,
    payoutConversion
  }) {
    const delivered = order.report != null;
    const inProgress = !delivered && order.inProgress === true;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "article",
      {
        className: `${styles$n.openCard} ${styles$n.openCardSimpleService}`,
        children: [
          delivered ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: styles$n.inProgressBadge,
              "aria-label": "View delivered bounty reveal report",
              onClick: (e) => {
                e.stopPropagation();
                onViewReport(order);
              },
              children: "View report"
            }
          ) : inProgress ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "button",
            {
              type: "button",
              className: styles$n.inProgressBadge,
              "aria-label": "View in-progress bounty reveal fulfillment",
              onClick: (e) => {
                e.stopPropagation();
                onShowInProgressView({
                  title: "Bounty Reveal — in progress",
                  subtitle: "Cancellation is locked while another user is revealing bounties for this target.",
                  quantityLabel: "Bounty reveal",
                  parties: order.contractId && order.fulfillerXid != null ? [
                    {
                      id: order.contractId,
                      partyId: order.fulfillerXid,
                      quantity: 1,
                      endsAt: order.endsAt ?? 0
                    }
                  ] : []
                });
              },
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.inProgressDot, "aria-hidden": "true" }),
                "In progress"
              ]
            }
          ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: styles$n.cancelOrder,
              "aria-label": "Cancel bounty reveal order",
              onClick: (e) => {
                e.stopPropagation();
                onCancel(order);
              },
              children: "×"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              className: `${styles$n.openCardBadge} ${styles$n.openCardBadgeGray}`,
              children: delivered ? "Bounty Reveal — delivered" : "Bounty Reveal — open"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRows, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRow, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Target" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(SimpleServiceTargetLink, { targetUserId: order.targetUserId }) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$n.openCardRow} tlm-payout-hover-scope`, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: delivered ? "Paid" : "Escrowed" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$n.openCardValue} ${styles$e.valueGray}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                PayoutValue,
                {
                  amount: order.escrowedPts,
                  conversion: payoutConversion,
                  label: "Bounty reveal escrowed payout",
                  className: styles$e.payoutValue
                }
              ) })
            ] })
          ] })
        ]
      }
    );
  }
  function ActiveFlightDelayCard({
    flightDelay,
    onCancel,
    payoutConversion
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "article",
      {
        className: `${styles$n.openCard} ${styles$n.openCardEmbargo}`,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: styles$n.cancelOrder,
              "aria-label": "Cancel flight delay order",
              onClick: (e) => {
                e.stopPropagation();
                onCancel(flightDelay);
              },
              children: "×"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "span",
            {
              className: `${styles$n.openCardBadge} ${styles$n.openCardBadgeRed}`,
              children: "Flight Delay — open"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRows, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRow, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Target" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(FlightDelayTargetLink, { targetUserId: flightDelay.targetUserId }) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$n.openCardRow} tlm-payout-hover-scope`, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Escrowed" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$n.openCardValue} ${styles$e.valueRed}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                PayoutValue,
                {
                  amount: flightDelay.escrowedPts,
                  conversion: payoutConversion,
                  label: "Flight delay escrowed payout",
                  className: styles$e.payoutValue
                }
              ) })
            ] })
          ] })
        ]
      }
    );
  }
  function ActiveSimpleServiceCard({
    config,
    service,
    onCancel,
    payoutConversion
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "article",
      {
        className: `${styles$n.openCard} ${styles$n.openCardSimpleService}`,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: styles$n.cancelOrder,
              "aria-label": `Cancel ${config.label.toLowerCase()} order`,
              onClick: (e) => {
                e.stopPropagation();
                onCancel(service);
              },
              children: "×"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "span",
            {
              className: `${styles$n.openCardBadge} ${styles$n.openCardBadgeGray}`,
              children: [
                config.label,
                " — open"
              ]
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRows, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRow, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Target" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(SimpleServiceTargetLink, { targetUserId: service.targetUserId }) })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$n.openCardRow} tlm-payout-hover-scope`, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Escrowed" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$n.openCardValue} ${styles$e.valueGray}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                PayoutValue,
                {
                  amount: service.escrowedPts,
                  conversion: payoutConversion,
                  label: `${config.label} escrowed payout`,
                  className: styles$e.payoutValue
                }
              ) })
            ] })
          ] })
        ]
      }
    );
  }
  function CollapsibleSidebarSection({
    title: title2,
    badges,
    expanded,
    onExpandedChange,
    sectionId,
    collapseLabel,
    expandLabel,
    children
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("section", { className: styles$n.collapsibleSection, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.sectionHeader, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.sectionHeaderStart, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: styles$n.sectionTitle, children: title2 }),
          !expanded && badges ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$n.sectionBadges, children: badges }) : null
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "button",
            className: styles$n.sectionChevronButton,
            "aria-expanded": expanded,
            "aria-controls": sectionId,
            "aria-label": expanded ? collapseLabel : expandLabel,
            onClick: () => onExpandedChange(!expanded),
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              ChevronIcon$1,
              {
                className: `${styles$n.sectionChevron} ${expanded ? styles$n.sectionChevronExpanded : ""}`
              }
            )
          }
        )
      ] }),
      expanded ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { id: sectionId, className: styles$n.sectionBody, children }) : null
    ] });
  }
  function ChevronIcon$1({ className }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "svg",
      {
        className,
        width: "12",
        height: "12",
        viewBox: "0 0 24 24",
        fill: "none",
        "aria-hidden": true,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "path",
          {
            d: "M6 9l6 6 6-6",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
          }
        )
      }
    );
  }
  function buildBuyerOrderInProgressView(order) {
    const orderLabel = CONTRACT_TYPE_LABELS[order.contractType];
    return {
      title: `${orderLabel} contract — in progress`,
      subtitle: `Cancellation is locked while another user is delivering ${orderLabel.toLowerCase()} for this contract.`,
      quantityLabel: `${orderLabel} claimed`,
      parties: order.activeContracts,
      pausableOrder: { id: order.id, isPaused: order.isPaused }
    };
  }
  function buildWithdrawalInProgressView(request) {
    return {
      title: "Withdrawal — in progress",
      subtitle: "Cancellation is locked while another user is fulfilling part of this request.",
      quantityLabel: "Xanax claimed",
      parties: request.activeFulfillments
    };
  }
  function buildBountyOrderInProgressView(order) {
    return {
      title: "Bounty contract — in progress",
      subtitle: "Cancellation is locked while another user is placing bounties for this order.",
      quantityLabel: "Bounties claimed",
      parties: order.activeContracts
    };
  }
  function ContractTypeQuantityBadge({
    type,
    quantityRemaining,
    inProgress,
    completed,
    onProgressClick,
    onInProgressClick,
    onCancelClick,
    onDismissClick,
    paused = false
  }) {
    const label2 = CONTRACT_TYPE_LABELS[type].toLowerCase();
    const formatted = quantityRemaining.toLocaleString("en-US");
    if (completed) {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "span",
        {
          className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeYellow} ${styles$n.sectionBadgeCompound}`,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "button",
              {
                type: "button",
                className: `${styles$n.sectionBadgeButton} ${styles$n.sectionBadgeCompoundMain}`,
                "aria-label": `View completed ${label2} contract progress`,
                onClick: (e) => {
                  e.stopPropagation();
                  onProgressClick();
                },
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    ContractTypeIcon,
                    {
                      type,
                      size: 12,
                      className: styles$n.sectionBadgeIcon
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.sectionBadgeCount, "aria-hidden": true, children: "✓" })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                type: "button",
                className: `${styles$n.sectionBadgeButton} ${styles$n.sectionBadgeCompoundDismiss}`,
                "aria-label": `Dismiss completed ${label2} contract`,
                onClick: (e) => {
                  e.stopPropagation();
                  onDismissClick();
                },
                children: "×"
              }
            )
          ]
        }
      );
    }
    if (inProgress) {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          className: `${styles$n.sectionBadge} ${paused ? styles$n.sectionBadgePaused : styles$n.sectionBadgeYellow} ${styles$n.sectionBadgeButton}`,
          "aria-label": `View in-progress ${label2} contract, ${formatted} remaining${paused ? ", paused" : ""}`,
          onClick: (e) => {
            e.stopPropagation();
            onInProgressClick();
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              ContractTypeIcon,
              {
                type,
                size: 12,
                className: styles$n.sectionBadgeIcon
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.sectionBadgeCount, children: formatted })
          ]
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "button",
      {
        type: "button",
        className: `${styles$n.sectionBadge} ${paused ? styles$n.sectionBadgePaused : `${styles$n.sectionBadgeBlue} ${styles$n.sectionBadgeBlueCancel}`} ${styles$n.sectionBadgeButton}`,
        "aria-label": `Cancel ${label2} buy order, ${formatted} remaining${paused ? ", paused" : ""}`,
        onClick: (e) => {
          e.stopPropagation();
          onCancelClick();
        },
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            ContractTypeIcon,
            {
              type,
              size: 12,
              className: styles$n.sectionBadgeIcon
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.sectionBadgeCount, children: formatted })
        ]
      }
    );
  }
  function WithdrawalQuantityBadge({
    quantityRemaining,
    inProgress,
    onInProgressClick,
    onCancelClick
  }) {
    const formatted = quantityRemaining.toLocaleString("en-US");
    if (inProgress) {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeYellow} ${styles$n.sectionBadgeButton}`,
          "aria-label": `View in-progress withdrawal contract, ${formatted} xanax remaining`,
          onClick: (e) => {
            e.stopPropagation();
            onInProgressClick();
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Pill, { size: 12, className: styles$n.sectionBadgeIcon, "aria-hidden": true }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.sectionBadgeCount, children: formatted })
          ]
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "button",
      {
        type: "button",
        className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeGreen} ${styles$n.sectionBadgeGreenCancel} ${styles$n.sectionBadgeButton}`,
        "aria-label": `Cancel withdrawal request, ${formatted} xanax remaining`,
        onClick: (e) => {
          e.stopPropagation();
          onCancelClick();
        },
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Pill, { size: 12, className: styles$n.sectionBadgeIcon, "aria-hidden": true }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.sectionBadgeCount, children: formatted })
        ]
      }
    );
  }
  function InsurancePolicyHeaderBadge({
    policy,
    onExpired,
    onFileClaim
  }) {
    const handleExpired = reactExports.useCallback(() => {
      onExpired(policy.id);
    }, [onExpired, policy.id]);
    const secondsRemaining = useContractCountdown(policy.endsAt, handleExpired);
    const shortLabel = INSURANCE_PLAN_SHORT_LABELS[policy.planId];
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "button",
      {
        type: "button",
        className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeGreen} ${styles$n.sectionBadgeButton}`,
        "aria-label": `${shortLabel} insurance — file claim`,
        onClick: (e) => {
          e.stopPropagation();
          onFileClaim(policy);
        },
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.sectionBadgeLabel, children: shortLabel }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.sectionBadgeCountdown, "aria-live": "polite", children: formatInsuranceCountdown(secondsRemaining) })
        ]
      }
    );
  }
  function BuySectionTypeBadge({ type, onExpand }) {
    const label2 = CONTRACT_TYPE_LABELS[type].toLowerCase();
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "button",
      {
        type: "button",
        className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeBlue} ${styles$n.sectionBadgeButton}`,
        "aria-label": `Expand buy ${label2} section`,
        onClick: (e) => {
          e.stopPropagation();
          onExpand();
        },
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          ContractTypeIcon,
          {
            type,
            size: 12,
            className: styles$n.sectionBadgeIcon
          }
        )
      }
    );
  }
  function BountyOrderHeaderBadge({
    order,
    inProgress,
    onInProgressClick,
    onCancel
  }) {
    const formatted = order.quantityRemaining.toLocaleString("en-US");
    if (inProgress) {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeYellow} ${styles$n.sectionBadgeButton}`,
          "aria-label": `View in-progress bounty contract, ${formatted} remaining`,
          onClick: (e) => {
            e.stopPropagation();
            onInProgressClick();
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Crosshair, { size: 12, className: styles$n.sectionBadgeIcon, "aria-hidden": true }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.sectionBadgeCount, children: formatted })
          ]
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "button",
      {
        type: "button",
        className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeRed} ${styles$n.sectionBadgeRedCancel} ${styles$n.sectionBadgeButton}`,
        "aria-label": `Cancel bounty order, ${formatted} remaining`,
        onClick: (e) => {
          e.stopPropagation();
          onCancel(order);
        },
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Crosshair, { size: 12, className: styles$n.sectionBadgeIcon, "aria-hidden": true }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.sectionBadgeCount, children: formatted })
        ]
      }
    );
  }
  const SERVICE_CATEGORY_BADGE_COLOR = {
    neutral: styles$n.sectionBadgeNeutral,
    disrupt: styles$n.sectionBadgeRed,
    other: styles$n.sectionBadgeGreen
  };
  const ServiceCategoryBadge = reactExports.forwardRef(function ServiceCategoryBadge2({ Icon: Icon2, name: name2, variant, onOpenModal }, ref) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "button",
      {
        ref,
        type: "button",
        className: `${styles$n.sectionBadge} ${SERVICE_CATEGORY_BADGE_COLOR[variant]} ${styles$n.sectionBadgeButton}`,
        "aria-label": `Open ${name2} services`,
        "aria-haspopup": "dialog",
        onClick: (e) => {
          e.stopPropagation();
          onOpenModal();
        },
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(Icon2, { size: 12, className: styles$n.sectionBadgeIcon, "aria-hidden": true }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.sectionBadgeLabel, children: name2 })
        ]
      }
    );
  });
  function ProductivityBoostHeaderBadge({
    boost,
    onCancel
  }) {
    const formatted = boost.companyId.toLocaleString("en-US");
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "button",
      {
        type: "button",
        className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeGreen} ${styles$n.sectionBadgeGreenCancel} ${styles$n.sectionBadgeButton}`,
        "aria-label": `Cancel productivity boost for company ${formatted}`,
        onClick: (e) => {
          e.stopPropagation();
          onCancel(boost);
        },
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(Building2, { size: 12, className: styles$n.sectionBadgeIcon, "aria-hidden": true })
      }
    );
  }
  function EmbargoHeaderBadge({
    embargo,
    onCancel
  }) {
    const formatted = embargo.targetUserId.toLocaleString("en-US");
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "button",
      {
        type: "button",
        className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeRed} ${styles$n.sectionBadgeRedCancel} ${styles$n.sectionBadgeButton}`,
        "aria-label": `Cancel embargo for target ${formatted}`,
        onClick: (e) => {
          e.stopPropagation();
          onCancel(embargo);
        },
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(Frown, { size: 12, className: styles$n.sectionBadgeIcon, "aria-hidden": true })
      }
    );
  }
  function FlightDelayHeaderBadge({
    flightDelay,
    onCancel
  }) {
    const formatted = flightDelay.targetUserId.toLocaleString("en-US");
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "button",
      {
        type: "button",
        className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeRed} ${styles$n.sectionBadgeRedCancel} ${styles$n.sectionBadgeButton}`,
        "aria-label": `Cancel flight delay for target ${formatted}`,
        onClick: (e) => {
          e.stopPropagation();
          onCancel(flightDelay);
        },
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(PlaneTakeoff, { size: 12, className: styles$n.sectionBadgeIcon, "aria-hidden": true })
      }
    );
  }
  function SimpleServiceHeaderBadge({
    service,
    onCancel
  }) {
    const config = SIMPLE_SERVICES[service.kind];
    const Icon2 = config.Icon;
    const formatted = service.targetUserId.toLocaleString("en-US");
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "button",
      {
        type: "button",
        className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeNeutral} ${styles$n.sectionBadgeNeutralCancel} ${styles$n.sectionBadgeButton}`,
        "aria-label": `Cancel ${config.label.toLowerCase()} for target ${formatted}`,
        onClick: (e) => {
          e.stopPropagation();
          onCancel(service);
        },
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(Icon2, { size: 12, className: styles$n.sectionBadgeIcon, "aria-hidden": true })
      }
    );
  }
  function buildReferencesInProgressView(order) {
    return {
      title: "References — in progress",
      subtitle: "Cancellation is locked while another user is pulling references for this target.",
      quantityLabel: "References",
      parties: order.contractId && order.fulfillerXid != null ? [
        {
          id: order.contractId,
          partyId: order.fulfillerXid,
          quantity: 1,
          endsAt: order.endsAt ?? 0
        }
      ] : []
    };
  }
  function ReferencesHeaderBadge({
    order,
    onCancel,
    onShowInProgressView,
    onViewReport
  }) {
    const formatted = order.targetUserId.toLocaleString("en-US");
    const delivered = order.report != null;
    const inProgress = !delivered && order.inProgress === true;
    if (delivered) {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeYellow} ${styles$n.sectionBadgeButton}`,
          "aria-label": `View delivered references report for target ${formatted}`,
          onClick: (e) => {
            e.stopPropagation();
            onViewReport(order);
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(UserSearch, { size: 12, className: styles$n.sectionBadgeIcon, "aria-hidden": true }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.sectionBadgeCount, "aria-hidden": true, children: "✓" })
          ]
        }
      );
    }
    if (inProgress) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeYellow} ${styles$n.sectionBadgeButton}`,
          "aria-label": `View in-progress references for target ${formatted}`,
          onClick: (e) => {
            e.stopPropagation();
            onShowInProgressView(buildReferencesInProgressView(order));
          },
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(UserSearch, { size: 12, className: styles$n.sectionBadgeIcon, "aria-hidden": true })
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "button",
      {
        type: "button",
        className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeNeutral} ${styles$n.sectionBadgeNeutralCancel} ${styles$n.sectionBadgeButton}`,
        "aria-label": `Cancel references for target ${formatted}`,
        onClick: (e) => {
          e.stopPropagation();
          onCancel(order);
        },
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(UserSearch, { size: 12, className: styles$n.sectionBadgeIcon, "aria-hidden": true })
      }
    );
  }
  function buildBountyRevealInProgressView(order) {
    return {
      title: "Bounty Reveal — in progress",
      subtitle: "Cancellation is locked while another user is revealing bounties for this target.",
      quantityLabel: "Bounty reveal",
      parties: order.contractId && order.fulfillerXid != null ? [
        {
          id: order.contractId,
          partyId: order.fulfillerXid,
          quantity: 1,
          endsAt: order.endsAt ?? 0
        }
      ] : []
    };
  }
  function BountyRevealHeaderBadge({
    order,
    onCancel,
    onShowInProgressView,
    onViewReport
  }) {
    const formatted = order.targetUserId.toLocaleString("en-US");
    const delivered = order.report != null;
    const inProgress = !delivered && order.inProgress === true;
    if (delivered) {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeYellow} ${styles$n.sectionBadgeButton}`,
          "aria-label": `View delivered bounty reveal report for target ${formatted}`,
          onClick: (e) => {
            e.stopPropagation();
            onViewReport(order);
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Locate, { size: 12, className: styles$n.sectionBadgeIcon, "aria-hidden": true }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.sectionBadgeCount, "aria-hidden": true, children: "✓" })
          ]
        }
      );
    }
    if (inProgress) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeYellow} ${styles$n.sectionBadgeButton}`,
          "aria-label": `View in-progress bounty reveal for target ${formatted}`,
          onClick: (e) => {
            e.stopPropagation();
            onShowInProgressView(buildBountyRevealInProgressView(order));
          },
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(Locate, { size: 12, className: styles$n.sectionBadgeIcon, "aria-hidden": true })
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "button",
      {
        type: "button",
        className: `${styles$n.sectionBadge} ${styles$n.sectionBadgeNeutral} ${styles$n.sectionBadgeNeutralCancel} ${styles$n.sectionBadgeButton}`,
        "aria-label": `Cancel bounty reveal for target ${formatted}`,
        onClick: (e) => {
          e.stopPropagation();
          onCancel(order);
        },
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(Locate, { size: 12, className: styles$n.sectionBadgeIcon, "aria-hidden": true })
      }
    );
  }
  function YourContractsBadges({
    visibleBuyerOrders,
    myRedeemingRequest,
    activeInsurancePolicies,
    activeBountyOrders,
    activeProductivityBoosts,
    activeEmbargos,
    activeReferences,
    activeBountyReveals,
    activeFlightDelays,
    activeSimpleServices,
    onShowInProgressView,
    onShowBuyerOrderProgress,
    onDismissCompletedBuyerOrder,
    onCancelBuyerOrder,
    onCancelMyRedeemingRequest,
    onFileInsuranceClaim,
    onInsuranceExpired,
    onCancelBountyOrder,
    onCancelProductivityBoost,
    onCancelEmbargo,
    onCancelReferences,
    onViewReferencesReport,
    onCancelBountyReveal,
    onViewBountyRevealReport,
    onCancelFlightDelay,
    onCancelSimpleService
  }) {
    const redeemingInProgress = ((myRedeemingRequest == null ? void 0 : myRedeemingRequest.activeFulfillments) ?? []).length > 0;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      activeProductivityBoosts.map((boost) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        ProductivityBoostHeaderBadge,
        {
          boost,
          onCancel: onCancelProductivityBoost
        },
        boost.id
      )),
      activeEmbargos.map((embargo) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        EmbargoHeaderBadge,
        {
          embargo,
          onCancel: onCancelEmbargo
        },
        embargo.id
      )),
      activeReferences.map((order) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        ReferencesHeaderBadge,
        {
          order,
          onCancel: onCancelReferences,
          onShowInProgressView,
          onViewReport: onViewReferencesReport
        },
        order.id
      )),
      activeBountyReveals.map((order) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        BountyRevealHeaderBadge,
        {
          order,
          onCancel: onCancelBountyReveal,
          onShowInProgressView,
          onViewReport: onViewBountyRevealReport
        },
        order.id
      )),
      activeFlightDelays.map((flightDelay) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        FlightDelayHeaderBadge,
        {
          flightDelay,
          onCancel: onCancelFlightDelay
        },
        flightDelay.id
      )),
      activeSimpleServices.map((service) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        SimpleServiceHeaderBadge,
        {
          service,
          onCancel: onCancelSimpleService
        },
        service.id
      )),
      activeBountyOrders.map((order) => {
        const inProgress = order.activeContracts.length > 0;
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          BountyOrderHeaderBadge,
          {
            order,
            inProgress,
            onInProgressClick: () => onShowInProgressView(buildBountyOrderInProgressView(order)),
            onCancel: onCancelBountyOrder
          },
          order.id
        );
      }),
      visibleBuyerOrders.map((order) => {
        const inProgress = order.activeContracts.length > 0;
        const completed = isCompletedBuyerOrder(order);
        return /* @__PURE__ */ jsxRuntimeExports.jsx(
          ContractTypeQuantityBadge,
          {
            type: order.contractType,
            quantityRemaining: order.quantityRemaining,
            inProgress,
            completed,
            paused: order.isPaused,
            onProgressClick: () => onShowBuyerOrderProgress(order),
            onInProgressClick: () => onShowInProgressView(buildBuyerOrderInProgressView(order)),
            onCancelClick: () => onCancelBuyerOrder(order),
            onDismissClick: () => onDismissCompletedBuyerOrder(order)
          },
          order.id
        );
      }),
      myRedeemingRequest ? /* @__PURE__ */ jsxRuntimeExports.jsx(
        WithdrawalQuantityBadge,
        {
          quantityRemaining: myRedeemingRequest.xanaxRemaining,
          inProgress: redeemingInProgress,
          onInProgressClick: () => onShowInProgressView(
            buildWithdrawalInProgressView(myRedeemingRequest)
          ),
          onCancelClick: () => onCancelMyRedeemingRequest(myRedeemingRequest)
        }
      ) : null,
      activeInsurancePolicies.map((policy) => /* @__PURE__ */ jsxRuntimeExports.jsx(
        InsurancePolicyHeaderBadge,
        {
          policy,
          onExpired: onInsuranceExpired,
          onFileClaim: onFileInsuranceClaim
        },
        policy.id
      ))
    ] });
  }
  const variantNeutral = "_variantNeutral_1iai8_2";
  const variantDisrupt = "_variantDisrupt_1iai8_14";
  const variantOther = "_variantOther_1iai8_26";
  const variantNeutralInteractive = "_variantNeutralInteractive_1iai8_37";
  const variantDisruptInteractive = "_variantDisruptInteractive_1iai8_48";
  const variantOtherInteractive = "_variantOtherInteractive_1iai8_59";
  const themeStyles = {
    variantNeutral,
    variantDisrupt,
    variantOther,
    variantNeutralInteractive,
    variantDisruptInteractive,
    variantOtherInteractive
  };
  const card$1 = "_card_4yqq6_1";
  const cardInteractive = "_cardInteractive_4yqq6_28";
  const cardDisabled = "_cardDisabled_4yqq6_36";
  const sizeGrid = "_sizeGrid_4yqq6_47";
  const sizeModalTile = "_sizeModalTile_4yqq6_52";
  const topBlock = "_topBlock_4yqq6_58";
  const icon = "_icon_4yqq6_66";
  const title$3 = "_title_4yqq6_71";
  const description = "_description_4yqq6_77";
  const bookCta = "_bookCta_4yqq6_82";
  const bookCtaLabel = "_bookCtaLabel_4yqq6_86";
  const styles$d = {
    card: card$1,
    cardInteractive,
    cardDisabled,
    sizeGrid,
    sizeModalTile,
    topBlock,
    icon,
    title: title$3,
    description,
    bookCta,
    bookCtaLabel
  };
  const VARIANT_CLASS$1 = {
    neutral: themeStyles.variantNeutral,
    disrupt: themeStyles.variantDisrupt,
    other: themeStyles.variantOther
  };
  const INTERACTIVE_VARIANT_CLASS = {
    neutral: themeStyles.variantNeutralInteractive,
    disrupt: themeStyles.variantDisruptInteractive,
    other: themeStyles.variantOtherInteractive
  };
  const ServiceBentoCard = reactExports.forwardRef(function ServiceBentoCard2({ Icon: Icon2, name: name2, description: description2, variant, layout: layout2 = "grid", onClick, disabled = false }, ref) {
    const isGrid = layout2 === "grid";
    const interactive = onClick !== void 0 && !disabled;
    const className = [
      styles$d.card,
      isGrid ? styles$d.sizeGrid : styles$d.sizeModalTile,
      VARIANT_CLASS$1[variant],
      interactive ? styles$d.cardInteractive : "",
      interactive ? INTERACTIVE_VARIANT_CLASS[variant] : "",
      disabled ? styles$d.cardDisabled : ""
    ].filter(Boolean).join(" ");
    const content = /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$d.topBlock, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Icon2, { className: styles$d.icon, strokeWidth: 1.75, "aria-hidden": true }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("h3", { className: styles$d.title, children: name2 })
      ] }),
      description2 ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$d.description, children: description2 }) : null,
      disabled ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$d.bookCta, children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$d.bookCtaLabel, children: "Coming soon" }) }) : interactive ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$d.bookCta, children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$d.bookCtaLabel, children: "Book service →" }) }) : null
    ] });
    if (interactive) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          ref,
          type: "button",
          className,
          onClick,
          "aria-haspopup": isGrid ? "dialog" : void 0,
          "aria-label": name2,
          children: content
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        ref,
        className,
        "aria-label": name2,
        children: content
      }
    );
  });
  const dialogWide = "_dialogWide_8c2s7_1";
  const header$1 = "_header_8c2s7_5";
  const headerTitle = "_headerTitle_8c2s7_12";
  const headerIcon = "_headerIcon_8c2s7_17";
  const serviceTileGrid = "_serviceTileGrid_8c2s7_25";
  const serviceTileItem = "_serviceTileItem_8c2s7_34";
  const wipTileGrid = "_wipTileGrid_8c2s7_42";
  const wipFeaturedItem = "_wipFeaturedItem_8c2s7_52";
  const styles$c = {
    dialogWide,
    header: header$1,
    headerTitle,
    headerIcon,
    serviceTileGrid,
    serviceTileItem,
    wipTileGrid,
    wipFeaturedItem
  };
  const SERVICE_BENTO_FEATURES = [
    {
      Icon: HatGlasses,
      name: "Reveal",
      description: "Spies, Loadout, Reference, FoF, Meditate, Bounty",
      services: [
        {
          name: "Spies",
          description: "Obtain full / partial / old battle stats of users & factions",
          Icon: HatGlasses,
          action: "spies"
        },
        {
          name: "Loadout",
          description: "Obtain a target's equipment",
          Icon: Swords,
          action: "loadout"
        },
        {
          name: "References",
          description: "View a target's employment and faction history",
          Icon: UserSearch,
          action: "references"
        },
        {
          name: "Friend or Foe",
          description: "See who's friended / blacklisted you",
          Icon: UserCheck,
          action: "friend-or-foe",
          featured: true
        },
        {
          name: "Meditation",
          description: "View someone's true level if they are level holding",
          Icon: Search,
          action: "meditation"
        },
        {
          name: "Bounty Reveal",
          description: "View lister of anonymous bounties",
          Icon: Locate,
          action: "bounty-reveal"
        }
      ],
      variant: "neutral"
    },
    {
      Icon: Crosshair,
      name: "Disrupt",
      description: "Bounties, Flight Delay, Embargo",
      services: [
        {
          name: "Bounties",
          description: "Place bulk bounties on a target",
          Icon: Crosshair,
          action: "bounties"
        },
        {
          name: "Flight Delay",
          description: "Extend a target's flight time by 1:30 – 2:00 hours",
          Icon: PlaneTakeoff,
          action: "flight-delay"
        },
        {
          name: "Embargo",
          description: "Halve a target's happiness",
          Icon: Frown,
          action: "embargo"
        }
      ],
      variant: "disrupt"
    },
    {
      Icon: HandCoins,
      name: "Other",
      description: "Insurance, Productivity Boost, Withdraw",
      services: [
        {
          name: "Insurance",
          description: "Get paid when you OD",
          Icon: HandCoins,
          action: "insurance"
        },
        {
          name: "Withdraw",
          description: "Withdraw xanax",
          Icon: Pill,
          action: "withdraw"
        },
        {
          name: "Productivity Boost",
          description: "Boost a company's productivity",
          Icon: Building2,
          action: "productivity"
        }
      ],
      variant: "other"
    }
  ];
  const LIVE_SERVICE_ACTIONS = /* @__PURE__ */ new Set([
    "bounties",
    "insurance",
    "withdraw",
    "embargo",
    "references",
    "bounty-reveal"
  ]);
  function isServiceActionEnabled(action) {
    return LIVE_SERVICE_ACTIONS.has(action);
  }
  function subtypeToAction(subtype) {
    return subtype === "productivity-boost" ? "productivity" : subtype;
  }
  function isOtherSubtypeEnabled(subtype) {
    return isServiceActionEnabled(subtypeToAction(subtype));
  }
  function isServiceCategoryEnabled(variant) {
    const category = SERVICE_BENTO_FEATURES.find((f) => f.variant === variant);
    if (!category) return false;
    return category.services.some(
      (service) => service.action !== void 0 && isServiceActionEnabled(service.action)
    );
  }
  const VARIANT_CLASS = {
    neutral: themeStyles.variantNeutral,
    disrupt: themeStyles.variantDisrupt,
    other: themeStyles.variantOther
  };
  function ServiceCategoryModal({
    open,
    feature,
    onClose,
    onOpenBountiesModal,
    onOpenInsuranceModal,
    onOpenWithdraw,
    onOpenProductivityBoost,
    onOpenEmbargo,
    onOpenFlightDelay,
    onOpenSimpleService
  }) {
    const insuranceTour = useInsuranceAdTourContext();
    const insuranceCardRef = reactExports.useRef(null);
    const insuranceSpotlightVisible = open && feature.variant === "other" && insuranceTour.phase === "insuranceCard";
    const insuranceSpotlightOpacity = useSpotlightFade(insuranceSpotlightVisible);
    const bountyTour = useBountyAdTourContext();
    const bountiesCardRef = reactExports.useRef(null);
    const bountiesSpotlightVisible = open && feature.variant === "disrupt" && bountyTour.phase === "bountiesCard";
    const bountiesSpotlightOpacity = useSpotlightFade(bountiesSpotlightVisible);
    reactExports.useEffect(() => {
      if (!open) return;
      const handleKeyDown = (e) => {
        if (e.key === "Escape") onClose();
      };
      window.addEventListener("keydown", handleKeyDown);
      return () => window.removeEventListener("keydown", handleKeyDown);
    }, [open, onClose]);
    const handleServiceAction = reactExports.useCallback(
      (action) => {
        if (!action) return;
        if (action === "insurance") insuranceTour.notifyInsuranceSelected();
        if (action === "bounties") bountyTour.notifyBountiesSelected();
        onClose();
        if (action === "bounties") onOpenBountiesModal();
        if (action === "insurance") onOpenInsuranceModal();
        if (action === "withdraw") onOpenWithdraw();
        if (action === "productivity") onOpenProductivityBoost();
        if (action === "embargo") onOpenEmbargo();
        if (action === "flight-delay") onOpenFlightDelay();
        if (isSimpleServiceId(action)) onOpenSimpleService(action);
      },
      [
        insuranceTour,
        bountyTour,
        onClose,
        onOpenBountiesModal,
        onOpenInsuranceModal,
        onOpenWithdraw,
        onOpenProductivityBoost,
        onOpenEmbargo,
        onOpenFlightDelay,
        onOpenSimpleService
      ]
    );
    if (!open) return null;
    const portalTarget = getExtensionShadowMount() ?? document.body;
    const { Icon: Icon2, name: name2, services, variant } = feature;
    const themeClass = VARIANT_CLASS[variant];
    const isWip = variant === "neutral";
    return reactDomExports.createPortal(
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: contractStyles.overlay,
          role: "presentation",
          onMouseDown: (e) => overlayMouseDownDismiss(e, onClose),
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "div",
              {
                className: `${contractStyles.dialog} ${styles$c.dialogWide} ${themeClass}`,
                role: "dialog",
                "aria-modal": "true",
                "aria-labelledby": "tlm-service-category-title",
                onClick: (e) => e.stopPropagation(),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$c.header, children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(Icon2, { className: styles$c.headerIcon, strokeWidth: 1.75, "aria-hidden": true }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "h2",
                      {
                        id: "tlm-service-category-title",
                        className: `${contractStyles.title} ${styles$c.headerTitle}`,
                        children: name2
                      }
                    )
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: isWip ? styles$c.wipTileGrid : styles$c.serviceTileGrid, children: services.map((service) => {
                    const serviceEnabled = service.action !== void 0 && isServiceActionEnabled(service.action);
                    return /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "li",
                      {
                        className: `${styles$c.serviceTileItem} ${isWip && service.featured ? styles$c.wipFeaturedItem : ""}`,
                        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                          ServiceBentoCard,
                          {
                            ref: service.action === "insurance" ? insuranceCardRef : service.action === "bounties" ? bountiesCardRef : void 0,
                            Icon: service.Icon,
                            name: service.name,
                            description: service.description,
                            variant,
                            layout: "modalTile",
                            disabled: service.action !== void 0 && !serviceEnabled,
                            onClick: serviceEnabled ? () => handleServiceAction(service.action) : void 0
                          }
                        )
                      },
                      service.name
                    );
                  }) })
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              PanelButtonTutorial,
              {
                visible: insuranceSpotlightVisible,
                opacity: insuranceSpotlightOpacity,
                fadeMs: 300,
                targetRef: insuranceCardRef,
                onTransitionEnd: () => {
                },
                portalTarget,
                layerZIndex: API_KEY_SPOTLIGHT_Z
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              PanelButtonTutorial,
              {
                visible: bountiesSpotlightVisible,
                opacity: bountiesSpotlightOpacity,
                fadeMs: 300,
                targetRef: bountiesCardRef,
                onTransitionEnd: () => {
                },
                portalTarget,
                layerZIndex: API_KEY_SPOTLIGHT_Z,
                caption: "Place bulk bounties on a target — no 10-cap."
              }
            )
          ]
        }
      ),
      portalTarget
    );
  }
  const RECOMMENDED_TORN_MIN = {
    losses: TIMELY_LOSS_TORN_PAY_MIN,
    escapes: RECOMMENDED_ESCAPE_STALEMATE_TORN_PAY_MIN,
    stalemates: RECOMMENDED_ESCAPE_STALEMATE_TORN_PAY_MIN
  };
  const RECOMMENDED_TORN_HINT = {
    losses: "$250k+ for timely losses",
    escapes: "$500k+ recommended",
    stalemates: "$500k+ recommended"
  };
  function getPriceValidationMessage(raw, contractType) {
    const singular = CONTRACT_TYPE_SINGULAR[contractType].toLowerCase();
    const trimmed = raw.trim();
    if (!trimmed) return null;
    const value = evaluateNumericInput(trimmed);
    if (value === null) {
      return `Enter a valid price (${formatExtensionPoints(BUYER_ORDER_PRICE_MIN)}–${formatExtensionPoints(BUYER_ORDER_PRICE_MAX)}, optional k/m/b).`;
    }
    if (!Number.isInteger(value)) {
      return "Price must be a whole number (e.g. 100k or 0.4m).";
    }
    if (value < BUYER_ORDER_PRICE_MIN) {
      return `Price per ${singular} must be at least ${formatExtensionPoints(BUYER_ORDER_PRICE_MIN)}.`;
    }
    if (value > BUYER_ORDER_PRICE_MAX) {
      return `Price per ${singular} cannot exceed ${formatExtensionPoints(BUYER_ORDER_PRICE_MAX)}.`;
    }
    return null;
  }
  function getQuantityValidationMessage(raw) {
    const trimmed = raw.trim();
    if (!trimmed) return null;
    const value = evaluateNumericInput(trimmed);
    if (value === null) {
      return `Enter a valid quantity (${BUYER_ORDER_QTY_MIN}–${BUYER_ORDER_QTY_MAX.toLocaleString("en-US")}, optional k/m/b).`;
    }
    if (!Number.isInteger(value)) {
      return "Quantity must be a whole number.";
    }
    if (value < BUYER_ORDER_QTY_MIN) {
      return `Quantity must be at least ${BUYER_ORDER_QTY_MIN.toLocaleString("en-US")}.`;
    }
    if (value > BUYER_ORDER_QTY_MAX) {
      return `Quantity cannot exceed ${BUYER_ORDER_QTY_MAX.toLocaleString("en-US")}.`;
    }
    return null;
  }
  function getSubmitDisabledReason(priceInput, quantityInput, price, quantity2, contractType) {
    const singular = CONTRACT_TYPE_SINGULAR[contractType].toLowerCase();
    const hasPriceText = priceInput.trim() !== "";
    const hasQuantityText = quantityInput.trim() !== "";
    if (!hasPriceText && !hasQuantityText) return null;
    if (price !== null && quantity2 !== null) return null;
    if (hasPriceText) {
      const priceMessage = getPriceValidationMessage(priceInput, contractType);
      if (priceMessage) return priceMessage;
    } else if (price === null && quantity2 !== null) {
      return `Enter a price per ${singular}.`;
    }
    if (hasQuantityText) {
      const quantityMessage = getQuantityValidationMessage(quantityInput);
      if (quantityMessage) return quantityMessage;
    } else if (quantity2 === null && price !== null) {
      return "Enter a quantity.";
    }
    return null;
  }
  function BuyersPanel({
    buyerOrders,
    balance,
    hasActiveFulfillment,
    onSubmitOrder,
    onCancelBuyerOrder,
    onShowInProgressView,
    onShowBuyerOrderProgress,
    onDismissCompletedBuyerOrder,
    myRedeemingRequest,
    onCancelMyRedeemingRequest,
    formResetKey,
    onAddBalance,
    payoutConversion,
    tornXid,
    activeInsurancePolicies,
    onInsuranceExpired,
    onOpenInsuranceModal,
    onFileInsuranceClaim,
    onDisableInsuranceAutoRenew,
    activeBountyOrders,
    onOpenBountiesModal,
    onCancelBountyOrder,
    onOpenWithdraw,
    onOpenProductivityBoost,
    activeProductivityBoosts,
    onCancelProductivityBoost,
    onOpenEmbargo,
    activeEmbargos,
    onCancelEmbargo,
    activeReferences,
    onCancelReferences,
    onViewReferencesReport,
    activeBountyReveals,
    onCancelBountyReveal,
    onViewBountyRevealReport,
    onOpenFlightDelay,
    activeFlightDelays,
    onCancelFlightDelay,
    onOpenSimpleService,
    activeSimpleServices,
    onCancelSimpleService
  }) {
    const [contractType, setContractType] = reactExports.useState(
      () => readStoredBuyContractTypeSync(tornXid) ?? "losses"
    );
    const [priceInput, setPriceInput] = reactExports.useState("");
    const [quantityInput, setQuantityInput] = reactExports.useState("");
    const [error2, setError] = reactExports.useState(null);
    const [sectionsExpanded, setSectionsExpanded] = reactExports.useState(
      () => readStoredBuyersPanelSectionsSync(tornXid)
    );
    const [serviceCategoryOpen, setServiceCategoryOpen] = reactExports.useState(null);
    const insuranceTour = useInsuranceAdTourContext();
    const otherCardRef = reactExports.useRef(null);
    const otherSpotlightVisible = insuranceTour.phase === "otherCard";
    const otherSpotlightOpacity = useSpotlightFade(otherSpotlightVisible);
    const bountyTour = useBountyAdTourContext();
    const disruptCardRef = reactExports.useRef(null);
    const disruptSpotlightVisible = bountyTour.phase === "disruptCard";
    const disruptSpotlightOpacity = useSpotlightFade(disruptSpotlightVisible);
    const extensionMount = getExtensionShadowMount();
    const openServiceCategory = reactExports.useCallback(
      (variant) => {
        setServiceCategoryOpen(variant);
        if (variant === "other") insuranceTour.notifyOtherCategoryOpened();
        if (variant === "disrupt") bountyTour.notifyDisruptCategoryOpened();
      },
      [insuranceTour, bountyTour]
    );
    const closeServiceCategory = reactExports.useCallback(() => {
      setServiceCategoryOpen(null);
      if (insuranceTour.phase === "insuranceCard") insuranceTour.cancelTour();
      if (bountyTour.phase === "bountiesCard") bountyTour.cancelTour();
    }, [insuranceTour, bountyTour]);
    reactExports.useEffect(() => {
      if (!otherSpotlightVisible) return;
      const id2 = requestAnimationFrame(() => {
        var _a2;
        (_a2 = otherCardRef.current) == null ? void 0 : _a2.scrollIntoView({ block: "nearest" });
      });
      return () => cancelAnimationFrame(id2);
    }, [otherSpotlightVisible]);
    reactExports.useEffect(() => {
      if (!disruptSpotlightVisible) return;
      const id2 = requestAnimationFrame(() => {
        var _a2;
        (_a2 = disruptCardRef.current) == null ? void 0 : _a2.scrollIntoView({ block: "nearest" });
      });
      return () => cancelAnimationFrame(id2);
    }, [disruptSpotlightVisible]);
    const setSectionExpanded = reactExports.useCallback(
      (section2, expanded) => {
        setSectionsExpanded((prev) => {
          const next = { ...prev, [section2]: expanded };
          void saveBuyersPanelSections(tornXid, next);
          return next;
        });
      },
      [tornXid]
    );
    reactExports.useEffect(() => {
      const cached = readStoredBuyContractTypeSync(tornXid) ?? "losses";
      setContractType(cached);
      let cancelled = false;
      void loadBuyContractType(tornXid).then((stored) => {
        if (!cancelled) setContractType(stored);
      });
      return () => {
        cancelled = true;
      };
    }, [tornXid]);
    reactExports.useEffect(() => {
      const cached = readStoredBuyersPanelSectionsSync(tornXid);
      setSectionsExpanded(cached);
      let cancelled = false;
      void loadBuyersPanelSections(tornXid).then((stored) => {
        if (!cancelled) setSectionsExpanded(stored);
      });
      return () => {
        cancelled = true;
      };
    }, [tornXid]);
    const handleContractTypeChange = (next) => {
      setContractType(next);
      setError(null);
      void saveBuyContractType(tornXid, next);
    };
    const contractLabel = CONTRACT_TYPE_LABELS[contractType];
    const contractSingular = CONTRACT_TYPE_SINGULAR[contractType].toLowerCase();
    reactExports.useEffect(() => {
      setPriceInput("");
      setQuantityInput("");
      setError(null);
    }, [formResetKey]);
    const price = reactExports.useMemo(() => parsePriceInput(priceInput), [priceInput]);
    const quantity2 = reactExports.useMemo(
      () => parseQuantityInput(quantityInput),
      [quantityInput]
    );
    const totalCost = price !== null && quantity2 !== null ? price * quantity2 : null;
    const maxAffordableQty = price !== null && price > 0 ? Math.min(Math.floor(balance / price), BUYER_ORDER_QTY_MAX) : null;
    const priceTornHint = reactExports.useMemo(() => {
      var _a2;
      const averagePrice = (_a2 = payoutConversion.price) == null ? void 0 : _a2.averagePrice;
      if (averagePrice == null || !priceInput.trim()) return null;
      const scriptAmount = evaluateNumericInput(priceInput);
      if (scriptAmount === null || !Number.isFinite(scriptAmount) || !Number.isInteger(scriptAmount) || scriptAmount <= 0) {
        return null;
      }
      const tornAmount = convertScriptDollarsToTornDollars(
        scriptAmount,
        averagePrice
      );
      const minimumTorn = RECOMMENDED_TORN_MIN[contractType];
      return {
        tornHint: `(${formatMoney(tornAmount)})`,
        belowMinimum: tornAmount < minimumTorn,
        minimumHint: RECOMMENDED_TORN_HINT[contractType]
      };
    }, [contractType, payoutConversion.price, priceInput]);
    const visibleBuyerOrders = buyerOrders;
    const openOrderForType = getOpenBuyerOrderForType(buyerOrders, contractType);
    const canSubmitNewOrder = openOrderForType === null && !hasActiveFulfillment;
    const redeemingInProgress = ((myRedeemingRequest == null ? void 0 : myRedeemingRequest.activeFulfillments) ?? []).length > 0;
    const submitEnabled = price !== null && quantity2 !== null;
    const submitDisabledReason = reactExports.useMemo(
      () => canSubmitNewOrder ? getSubmitDisabledReason(
        priceInput,
        quantityInput,
        price,
        quantity2,
        contractType
      ) : null,
      [
        canSubmitNewOrder,
        priceInput,
        quantityInput,
        price,
        quantity2,
        contractType
      ]
    );
    const handleSubmit = () => {
      if (openOrderForType) {
        setError(
          `You already have an open ${CONTRACT_TYPE_LABELS[contractType].toLowerCase()} contract.`
        );
        return;
      }
      if (hasActiveFulfillment) {
        setError("Finish your active contract before posting a new buy order.");
        return;
      }
      if (price === null) {
        setError(
          `Enter a valid price (${BUYER_ORDER_PRICE_MIN.toLocaleString("en-US")}–${BUYER_ORDER_PRICE_MAX.toLocaleString("en-US")}, optional k/m/b).`
        );
        return;
      }
      if (price < BUYER_ORDER_PRICE_MIN) {
        setError(
          `Price per ${contractSingular} must be at least ${formatExtensionPoints(BUYER_ORDER_PRICE_MIN)}.`
        );
        return;
      }
      if (quantity2 === null || quantity2 < BUYER_ORDER_QTY_MIN) {
        setError(
          `Enter a valid quantity (${BUYER_ORDER_QTY_MIN}–${BUYER_ORDER_QTY_MAX.toLocaleString("en-US")}).`
        );
        return;
      }
      if (quantity2 > BUYER_ORDER_QTY_MAX) {
        setError(
          `Quantity cannot exceed ${BUYER_ORDER_QTY_MAX.toLocaleString("en-US")}.`
        );
        return;
      }
      if (totalCost !== null && totalCost > balance) {
        setError("insufficient_balance");
        return;
      }
      setError(null);
      onSubmitOrder(contractType, price, quantity2);
    };
    const hasYourContractsBadges = visibleBuyerOrders.length > 0 || myRedeemingRequest !== null || activeInsurancePolicies.length > 0 || activeBountyOrders.length > 0 || activeProductivityBoosts.length > 0 || activeEmbargos.length > 0 || activeReferences.length > 0 || activeBountyReveals.length > 0 || activeFlightDelays.length > 0 || activeSimpleServices.length > 0;
    const yourContractsBadges = hasYourContractsBadges ? /* @__PURE__ */ jsxRuntimeExports.jsx(
      YourContractsBadges,
      {
        visibleBuyerOrders,
        myRedeemingRequest,
        activeInsurancePolicies,
        activeBountyOrders,
        activeProductivityBoosts,
        activeEmbargos,
        activeReferences,
        activeBountyReveals,
        activeFlightDelays,
        activeSimpleServices,
        onShowInProgressView,
        onShowBuyerOrderProgress,
        onDismissCompletedBuyerOrder,
        onCancelBuyerOrder,
        onCancelMyRedeemingRequest,
        onFileInsuranceClaim,
        onInsuranceExpired,
        onCancelBountyOrder,
        onCancelProductivityBoost,
        onCancelEmbargo,
        onCancelReferences,
        onViewReferencesReport,
        onCancelBountyReveal,
        onViewBountyRevealReport,
        onCancelFlightDelay,
        onCancelSimpleService
      }
    ) : void 0;
    const buyTitle = sectionsExpanded.buy ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      "Buy",
      " ",
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        ContractTypePicker,
        {
          variant: "inline",
          value: contractType,
          onChange: handleContractTypeChange,
          "aria-label": "Contract type to buy"
        }
      )
    ] }) : "Buy";
    const buyBadges = /* @__PURE__ */ jsxRuntimeExports.jsx(
      BuySectionTypeBadge,
      {
        type: contractType,
        onExpand: () => setSectionExpanded("buy", true)
      }
    );
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.panel, role: "region", "aria-label": "Your contracts", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        CollapsibleSidebarSection,
        {
          title: "Your contracts",
          badges: yourContractsBadges,
          expanded: sectionsExpanded.yourContracts,
          onExpandedChange: (next) => setSectionExpanded("yourContracts", next),
          sectionId: "tlm-your-contracts-body",
          collapseLabel: "Collapse Your contracts",
          expandLabel: "Expand Your contracts",
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openList, children: [
            activeProductivityBoosts.map((boost) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              ActiveProductivityBoostCard,
              {
                boost,
                onCancel: onCancelProductivityBoost,
                payoutConversion
              },
              boost.id
            )),
            activeEmbargos.map((embargo) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              ActiveEmbargoCard,
              {
                embargo,
                onCancel: onCancelEmbargo,
                onShowInProgressView,
                payoutConversion
              },
              embargo.id
            )),
            activeReferences.map((order) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              ActiveReferencesCard,
              {
                order,
                onCancel: onCancelReferences,
                onShowInProgressView,
                onViewReport: onViewReferencesReport,
                payoutConversion
              },
              order.id
            )),
            activeBountyReveals.map((order) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              ActiveBountyRevealCard,
              {
                order,
                onCancel: onCancelBountyReveal,
                onShowInProgressView,
                onViewReport: onViewBountyRevealReport,
                payoutConversion
              },
              order.id
            )),
            activeFlightDelays.map((flightDelay) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              ActiveFlightDelayCard,
              {
                flightDelay,
                onCancel: onCancelFlightDelay,
                payoutConversion
              },
              flightDelay.id
            )),
            activeSimpleServices.map((service) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              ActiveSimpleServiceCard,
              {
                config: SIMPLE_SERVICES[service.kind],
                service,
                onCancel: onCancelSimpleService,
                payoutConversion
              },
              service.id
            )),
            activeBountyOrders.map((order) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              ActiveBountyOrderCard,
              {
                order,
                onCancel: onCancelBountyOrder,
                onShowInProgressView,
                payoutConversion
              },
              order.id
            )),
            activeInsurancePolicies.map((policy) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              ActiveInsuranceCard,
              {
                policy,
                onFileClaim: onFileInsuranceClaim,
                onExpired: onInsuranceExpired,
                onDisableAutoRenew: onDisableInsuranceAutoRenew,
                payoutConversion
              },
              policy.id
            )),
            myRedeemingRequest && /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "article",
              {
                className: `${styles$n.openCard} ${styles$n.openCardWithdraw}`,
                children: [
                  redeemingInProgress ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "button",
                    {
                      type: "button",
                      className: styles$n.inProgressBadge,
                      "aria-label": "View in-progress fulfillments",
                      onClick: (e) => {
                        e.stopPropagation();
                        onShowInProgressView({
                          title: "Withdrawal — in progress",
                          subtitle: "Cancellation is locked while another user is fulfilling part of this request.",
                          quantityLabel: "Xanax claimed",
                          parties: myRedeemingRequest.activeFulfillments
                        });
                      },
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.inProgressDot, "aria-hidden": "true" }),
                        "In progress"
                      ]
                    }
                  ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      className: styles$n.cancelOrder,
                      "aria-label": "Cancel withdrawal request",
                      onClick: (e) => {
                        e.stopPropagation();
                        onCancelMyRedeemingRequest(myRedeemingRequest);
                      },
                      children: "×"
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$n.openCardBadge} ${styles$n.openCardBadgeGreen}`, children: "Withdrawal contract — open" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRows, children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRow, children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Quantity" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$n.openCardValue, children: [
                        redeemingRequestUncompletedQuantity(
                          myRedeemingRequest
                        ).toLocaleString("en-US"),
                        "/",
                        myRedeemingRequest.quantity.toLocaleString("en-US")
                      ] })
                    ] }),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$n.openCardRow} tlm-payout-hover-scope`, children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Escrowed" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$n.openCardValue, children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                          PayoutValue,
                          {
                            amount: getWithdrawTotalDebit(
                              myRedeemingRequest.xanaxRemaining
                            ),
                            conversion: payoutConversion,
                            label: "Withdrawal escrowed payout remaining",
                            className: styles$n.openCardValue
                          }
                        ),
                        " / ",
                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                          PayoutValue,
                          {
                            amount: getWithdrawTotalDebit(myRedeemingRequest.quantity),
                            conversion: payoutConversion,
                            label: "Withdrawal escrowed payout total",
                            className: styles$n.openCardValue
                          }
                        )
                      ] })
                    ] })
                  ] })
                ]
              },
              myRedeemingRequest.id
            ),
            visibleBuyerOrders.map((order) => {
              const orderType = order.contractType;
              const orderLabel = CONTRACT_TYPE_LABELS[orderType];
              const orderSingular = CONTRACT_TYPE_SINGULAR[orderType].toLowerCase();
              const orderInProgress = order.activeContracts.length > 0;
              const orderCompleted = isCompletedBuyerOrder(order);
              return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "article",
                {
                  className: `${styles$n.openCard} ${styles$n.openCardClickable} ${orderCompleted ? styles$n.openCardClosed : styles$n.openCardOwn}`,
                  role: "button",
                  tabIndex: 0,
                  "aria-label": `View ${orderLabel.toLowerCase()} contract progress`,
                  onClick: () => onShowBuyerOrderProgress(order),
                  onKeyDown: (e) => {
                    if (e.key === "Enter" || e.key === " ") {
                      e.preventDefault();
                      onShowBuyerOrderProgress(order);
                    }
                  },
                  children: [
                    orderCompleted ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        className: styles$n.cancelOrder,
                        "aria-label": `Dismiss completed ${orderLabel.toLowerCase()} contract`,
                        onClick: (e) => {
                          e.stopPropagation();
                          onDismissCompletedBuyerOrder(order);
                        },
                        children: "×"
                      }
                    ) : orderInProgress ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      "button",
                      {
                        type: "button",
                        className: styles$n.inProgressBadge,
                        "aria-label": `View in-progress ${orderLabel.toLowerCase()} contracts`,
                        onClick: (e) => {
                          e.stopPropagation();
                          onShowInProgressView({
                            title: `${orderLabel} contract — in progress`,
                            subtitle: `Cancellation is locked while another user is delivering ${orderLabel.toLowerCase()} for this contract.`,
                            quantityLabel: `${orderLabel} claimed`,
                            parties: order.activeContracts,
                            pausableOrder: { id: order.id, isPaused: order.isPaused }
                          });
                        },
                        children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.inProgressDot, "aria-hidden": "true" }),
                          "In progress"
                        ]
                      }
                    ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        className: styles$n.cancelOrder,
                        "aria-label": `Cancel ${orderLabel.toLowerCase()} buy order and refund remaining balance`,
                        onClick: (e) => {
                          e.stopPropagation();
                          onCancelBuyerOrder(order);
                        },
                        children: "×"
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "span",
                      {
                        className: `${styles$n.openCardBadge} ${orderCompleted ? styles$n.openCardBadgeClosed : order.isPaused ? styles$n.openCardBadgePaused : ""}`,
                        children: getContractTypeBadge(
                          orderType,
                          orderCompleted ? "closed" : order.isPaused ? "paused" : "open"
                        )
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRows, children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.openCardRow, children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Quantity" }),
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$n.openCardValue, children: [
                          buyerOrderUncompletedQuantity(order).toLocaleString(
                            "en-US"
                          ),
                          "/",
                          order.quantity.toLocaleString("en-US")
                        ] })
                      ] }),
                      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$n.openCardRow} tlm-payout-hover-scope`, children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.openCardLabel, children: "Escrowed" }),
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$n.openCardValue, children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            PayoutValue,
                            {
                              amount: getBuyerOrderRefund(order),
                              conversion: payoutConversion,
                              label: `${orderSingular} contract escrowed payout remaining`,
                              className: styles$n.openCardValue
                            }
                          ),
                          " / ",
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            PayoutValue,
                            {
                              amount: order.escrowedTotal,
                              conversion: payoutConversion,
                              label: `${orderSingular} contract escrowed payout total`,
                              className: styles$n.openCardValue
                            }
                          )
                        ] })
                      ] })
                    ] })
                  ]
                },
                order.id
              );
            })
          ] })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        CollapsibleSidebarSection,
        {
          title: buyTitle,
          badges: buyBadges,
          expanded: sectionsExpanded.buy,
          onExpandedChange: (next) => setSectionExpanded("buy", next),
          sectionId: "tlm-buy-contracts-body",
          collapseLabel: "Collapse buy section",
          expandLabel: "Expand buy section",
          children: !canSubmitNewOrder ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$n.formDisabled, children: openOrderForType ? `Close your open ${contractLabel.toLowerCase()} contract before posting a new one.` : "Finish your active contract before posting a new buy order." }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "form",
            {
              className: styles$n.form,
              onSubmit: (e) => {
                e.preventDefault();
                handleSubmit();
              },
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.field, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: styles$n.label, htmlFor: "tlm-buyer-price", children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.labelText, children: getPricePerLabel(contractType) }),
                    priceTornHint && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "span",
                        {
                          className: `${styles$n.labelPostfix} ${priceTornHint.belowMinimum ? styles$n.labelPostfixWarning : ""}`,
                          children: priceTornHint.tornHint
                        }
                      ),
                      priceTornHint.belowMinimum && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.timelyLossHint, children: priceTornHint.minimumHint })
                    ] })
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    PtsAmountInput,
                    {
                      id: "tlm-buyer-price",
                      value: priceInput,
                      onChange: (next) => {
                        setPriceInput(next);
                        setError(null);
                      },
                      max: BUYER_ORDER_PRICE_MAX,
                      referenceMax: balance,
                      sanitize: sanitizePriceInput,
                      inputMode: "decimal",
                      placeholder: "e.g. 100k, 0.4m",
                      hasError: Boolean(error2 && price === null && priceInput)
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$n.field, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: styles$n.label, htmlFor: "tlm-buyer-quantity", children: "Quantity" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    PtsAmountInput,
                    {
                      id: "tlm-buyer-quantity",
                      value: quantityInput,
                      onChange: (next) => {
                        setQuantityInput(next);
                        setError(null);
                      },
                      max: BUYER_ORDER_QTY_MAX,
                      referenceMax: maxAffordableQty ?? 0,
                      symbolLabel: "MAX",
                      symbolDisabled: maxAffordableQty === null,
                      sanitize: sanitizeQuantityInput,
                      inputMode: "numeric",
                      placeholder: "e.g. 50, 10k",
                      hasError: Boolean(error2 && quantity2 === null && quantityInput)
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$n.totalRow} tlm-payout-hover-scope`, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.totalLabel, children: "Total cost" }),
                  totalCost !== null ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                    PayoutValue,
                    {
                      amount: totalCost,
                      conversion: payoutConversion,
                      label: "Buy order total cost",
                      className: styles$n.totalValue
                    }
                  ) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$n.totalValue, children: "0" })
                ] }),
                error2 === "insufficient_balance" ? /* @__PURE__ */ jsxRuntimeExports.jsx(InsufficientBalanceMessage, { onAddBalance }) : error2 && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$n.error, children: error2 }),
                !submitEnabled && submitDisabledReason && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$n.error, children: submitDisabledReason }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "submit",
                    className: styles$n.submit,
                    disabled: !submitEnabled,
                    children: "Submit"
                  }
                )
              ]
            }
          )
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        CollapsibleSidebarSection,
        {
          title: "Services",
          badges: /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: SERVICE_BENTO_FEATURES.map((feature) => /* @__PURE__ */ jsxRuntimeExports.jsx(
            ServiceCategoryBadge,
            {
              ref: feature.variant === "other" ? otherCardRef : feature.variant === "disrupt" ? disruptCardRef : void 0,
              Icon: feature.Icon,
              name: feature.name,
              variant: feature.variant,
              onOpenModal: () => openServiceCategory(feature.variant)
            },
            feature.variant
          )) }),
          expanded: sectionsExpanded.services,
          onExpandedChange: (next) => setSectionExpanded("services", next),
          sectionId: "tlm-services-body",
          collapseLabel: "Collapse services section",
          expandLabel: "Expand services section",
          children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$n.servicesButtons, children: SERVICE_BENTO_FEATURES.map((feature) => {
            const categoryEnabled = isServiceCategoryEnabled(feature.variant);
            return /* @__PURE__ */ jsxRuntimeExports.jsx(
              ServiceBentoCard,
              {
                ref: feature.variant === "other" ? otherCardRef : feature.variant === "disrupt" ? disruptCardRef : void 0,
                Icon: feature.Icon,
                name: feature.name,
                description: feature.description,
                variant: feature.variant,
                disabled: !categoryEnabled,
                onClick: categoryEnabled ? () => openServiceCategory(feature.variant) : void 0
              },
              feature.name
            );
          }) })
        }
      ),
      serviceCategoryOpen !== null ? /* @__PURE__ */ jsxRuntimeExports.jsx(
        ServiceCategoryModal,
        {
          open: true,
          feature: SERVICE_BENTO_FEATURES.find(
            (f) => f.variant === serviceCategoryOpen
          ),
          onClose: closeServiceCategory,
          onOpenBountiesModal,
          onOpenInsuranceModal,
          onOpenWithdraw,
          onOpenProductivityBoost,
          onOpenEmbargo,
          onOpenFlightDelay,
          onOpenSimpleService
        }
      ) : null,
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PanelButtonTutorial,
        {
          visible: otherSpotlightVisible,
          opacity: otherSpotlightOpacity,
          fadeMs: 300,
          targetRef: otherCardRef,
          onTransitionEnd: () => {
          },
          portalTarget: extensionMount,
          layerZIndex: EXTENSION_SPOTLIGHT_Z,
          layoutKey: `${sectionsExpanded.services}:${serviceCategoryOpen}`
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PanelButtonTutorial,
        {
          visible: disruptSpotlightVisible,
          opacity: disruptSpotlightOpacity,
          fadeMs: 300,
          targetRef: disruptCardRef,
          onTransitionEnd: () => {
          },
          portalTarget: extensionMount,
          layerZIndex: EXTENSION_SPOTLIGHT_Z,
          layoutKey: `${sectionsExpanded.services}:${serviceCategoryOpen}`,
          caption: "Open Disrupt — bulk bounties live here."
        }
      )
    ] });
  }
  const STORAGE_KEY$3 = "shortcut_button_intro_seen";
  async function hasSeenShortcutButtonTutorial() {
    try {
      return await getPlatformRuntime().storage.get(STORAGE_KEY$3) === true;
    } catch {
      return false;
    }
  }
  async function markShortcutButtonTutorialSeen() {
    try {
      await getPlatformRuntime().storage.set(STORAGE_KEY$3, true);
    } catch {
    }
  }
  const STORAGE_KEY$2 = "turn_in_highlight_pending";
  async function hasPendingTurnInHighlight() {
    try {
      return await getPlatformRuntime().storage.get(STORAGE_KEY$2) === true;
    } catch {
      return false;
    }
  }
  async function markTurnInHighlightPending() {
    try {
      await getPlatformRuntime().storage.set(STORAGE_KEY$2, true);
    } catch {
    }
  }
  async function clearTurnInHighlightPending() {
    try {
      await getPlatformRuntime().storage.set(STORAGE_KEY$2, false);
    } catch {
    }
  }
  const panel$3 = "_panel_jmw4q_1";
  const badge$1 = "_badge_jmw4q_11";
  const badgeCompleted = "_badgeCompleted_jmw4q_25";
  const headline = "_headline_jmw4q_31";
  const timer$1 = "_timer_jmw4q_40";
  const timerHint = "_timerHint_jmw4q_50";
  const details = "_details_jmw4q_56";
  const row$3 = "_row_jmw4q_66";
  const rowLabel$1 = "_rowLabel_jmw4q_79";
  const rowValue$1 = "_rowValue_jmw4q_87";
  const rowValuePay = "_rowValuePay_jmw4q_94";
  const sellerLink$1 = "_sellerLink_jmw4q_101";
  const turnInSection = "_turnInSection_jmw4q_114";
  const turnInRow = "_turnInRow_jmw4q_122";
  const shortcutButton = "_shortcutButton_jmw4q_128";
  const partyValue = "_partyValue_jmw4q_159";
  const turnInButton = "_turnInButton_jmw4q_168";
  const turnInButtonHighlight = "_turnInButtonHighlight_jmw4q_200";
  const closeButton$1 = "_closeButton_jmw4q_216";
  const turnInError = "_turnInError_jmw4q_241";
  const styles$b = {
    panel: panel$3,
    badge: badge$1,
    badgeCompleted,
    headline,
    timer: timer$1,
    timerHint,
    details,
    row: row$3,
    rowLabel: rowLabel$1,
    rowValue: rowValue$1,
    rowValuePay,
    sellerLink: sellerLink$1,
    turnInSection,
    turnInRow,
    shortcutButton,
    partyValue,
    turnInButton,
    turnInButtonHighlight,
    closeButton: closeButton$1,
    turnInError
  };
  function ContractTurnInActions({
    shortcutLabel,
    shortcutHref,
    onTurnIn,
    turnInState,
    turnInError: turnInError2
  }) {
    const turnInLoading = turnInState === "loading";
    const shortcutRef = reactExports.useRef(null);
    const [spotlightVisible, setSpotlightVisible] = reactExports.useState(false);
    const [spotlightOpacity, setSpotlightOpacity] = reactExports.useState(0);
    const [turnInHighlight, setTurnInHighlight] = reactExports.useState(false);
    const extensionMount = getExtensionShadowMount();
    reactExports.useEffect(() => {
      let cancelled = false;
      void hasSeenShortcutButtonTutorial().then((seen) => {
        if (cancelled || seen) return;
        setSpotlightVisible(true);
        void markShortcutButtonTutorialSeen();
      });
      void Promise.all([
        hasPendingTurnInHighlight(),
        hasFirstContractCompleted()
      ]).then(([pending, completed]) => {
        if (cancelled || !pending || completed) return;
        setTurnInHighlight(true);
      });
      return () => {
        cancelled = true;
      };
    }, []);
    const armTurnInHighlight = async () => {
      if (await hasFirstContractCompleted()) return false;
      await markTurnInHighlightPending();
      return true;
    };
    reactExports.useEffect(() => {
      if (!spotlightVisible) {
        setSpotlightOpacity(0);
        return;
      }
      const id2 = requestAnimationFrame(() => {
        requestAnimationFrame(() => setSpotlightOpacity(1));
      });
      return () => cancelAnimationFrame(id2);
    }, [spotlightVisible]);
    const dismissSpotlight = () => {
      if (spotlightVisible) setSpotlightVisible(false);
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PanelButtonTutorial,
        {
          visible: spotlightVisible,
          opacity: spotlightOpacity,
          fadeMs: 300,
          targetRef: shortcutRef,
          onTransitionEnd: () => {
          },
          portalTarget: extensionMount,
          layerZIndex: EXTENSION_SPOTLIGHT_Z,
          layoutKey: shortcutLabel
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.turnInSection, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.turnInRow, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "a",
            {
              ref: shortcutRef,
              href: shortcutHref,
              className: styles$b.shortcutButton,
              ...externalLinkProps(),
              onClick: (e) => {
                dismissSpotlight();
                if (isWebPlatform()) {
                  void armTurnInHighlight().then((armed) => {
                    if (armed) setTurnInHighlight(true);
                  });
                  return;
                }
                if (e.button === 0 && !e.metaKey && !e.ctrlKey && !e.shiftKey && !e.altKey) {
                  e.preventDefault();
                  void armTurnInHighlight().finally(() => {
                    window.location.href = shortcutHref;
                  });
                } else {
                  void armTurnInHighlight();
                }
              },
              "aria-label": shortcutLabel === "Attack" ? "Open attack page for contract target" : shortcutLabel === "Bounty" ? "Open Torn bounties page to place bounty" : shortcutLabel === "Special" ? "Open Torn special company page to boost productivity" : shortcutLabel === "Embargo" ? "Open Torn special company page to embargo target" : shortcutLabel === "Delay" ? "Open Torn special company page to delay target" : "Open items page to send Xanax",
              children: shortcutLabel
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: `${styles$b.turnInButton} ${turnInHighlight ? styles$b.turnInButtonHighlight : ""}`,
              onClick: () => {
                dismissSpotlight();
                if (turnInHighlight) {
                  setTurnInHighlight(false);
                  void clearTurnInHighlightPending();
                }
                onTurnIn();
              },
              disabled: turnInLoading,
              "aria-busy": turnInLoading,
              children: turnInLoading ? "Verifying…" : "Turn in contract"
            }
          )
        ] }),
        turnInError2 && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$b.turnInError, role: "alert", children: turnInError2 })
      ] })
    ] });
  }
  const wrap$2 = "_wrap_1nwp6_1";
  const tooltip$1 = "_tooltip_1nwp6_8";
  const copyButton = "_copyButton_1nwp6_48";
  const styles$a = {
    wrap: wrap$2,
    tooltip: tooltip$1,
    copyButton
  };
  function CopyIdButton({
    id: id2,
    text: text2,
    label: label2 = "Copy ID",
    copiedLabel = "Copied to clipboard"
  }) {
    const [copied, setCopied] = reactExports.useState(false);
    const copyValue = text2 ?? (id2 !== void 0 ? String(id2) : "");
    const handleCopy = reactExports.useCallback(async () => {
      if (!copyValue) return;
      try {
        await navigator.clipboard.writeText(copyValue);
        setCopied(true);
        globalThis.setTimeout(() => setCopied(false), 2e3);
      } catch {
      }
    }, [copyValue]);
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$a.wrap, children: [
      copied && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$a.tooltip, role: "status", children: copiedLabel }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          className: styles$a.copyButton,
          onClick: () => void handleCopy(),
          "aria-label": copied ? copiedLabel : label2,
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(Copy, { size: 16, strokeWidth: 2, "aria-hidden": true })
        }
      )
    ] });
  }
  function ActiveContractPanel({
    contract,
    secondsRemaining,
    onTurnIn,
    turnInState,
    turnInError: turnInError2,
    payoutConversion
  }) {
    const { listing, contractType, quantity: quantity2, lossesRemaining, lossesVerified } = contract;
    const verified = Math.min(lossesVerified ?? 0, quantity2);
    const remaining = Math.min(
      lossesRemaining ?? Math.max(0, quantity2 - verified),
      quantity2
    );
    const totalPayout = listing.payPerLoss * quantity2;
    const verifiedLabel = `${CONTRACT_TYPE_LABELS[contractType]} verified`;
    const payPerLabel = getPayPerLabel(contractType);
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.panel, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$b.badge, children: "Active contract" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$b.timer, children: formatCountdown(secondsRemaining) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$b.timerHint, children: "remaining to fulfill" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.details, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Target" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.partyValue, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "a",
              {
                href: getSellerProfileUrl(listing.sellerId),
                className: styles$b.sellerLink,
                target: "_blank",
                rel: "noopener noreferrer",
                children: formatSellerId(listing.sellerId)
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              CopyIdButton,
              {
                id: listing.sellerId,
                label: "Copy target ID",
                copiedLabel: "Copied"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: verifiedLabel }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$b.rowValue, children: [
            verified,
            "/",
            quantity2
          ] })
        ] }),
        remaining > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Still to fulfill" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowValue, children: remaining })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$b.row} tlm-payout-hover-scope`, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: payPerLabel }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PayoutValue,
            {
              amount: listing.payPerLoss,
              conversion: payoutConversion,
              label: payPerLabel,
              className: styles$b.rowValuePay
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$b.row} tlm-payout-hover-scope`, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Pay" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PayoutValue,
            {
              amount: totalPayout,
              conversion: payoutConversion,
              label: "Total payout",
              className: styles$b.rowValuePay
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        ContractTurnInActions,
        {
          shortcutLabel: "Attack",
          shortcutHref: getTornAttackUrl(listing.sellerId),
          onTurnIn,
          turnInState,
          turnInError: turnInError2
        }
      )
    ] });
  }
  function ContractCompleteActions({ onClose }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$b.turnInSection, children: /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: styles$b.closeButton, onClick: onClose, children: "Close" }) });
  }
  function CompletedContractPanel({
    contract,
    onClose,
    payoutConversion
  }) {
    const { listing, contractType, quantity: quantity2, lossesVerified } = contract;
    const verified = Math.min(lossesVerified ?? quantity2, quantity2);
    const totalPayout = listing.payPerLoss * quantity2;
    const verifiedLabel = `${CONTRACT_TYPE_LABELS[contractType]} verified`;
    const payPerLabel = getPayPerLabel(contractType);
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.panel, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: `${styles$b.badge} ${styles$b.badgeCompleted}`, children: "Completed contract" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: styles$b.headline, children: "Contract Complete!" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.details, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Target" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.partyValue, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "a",
              {
                href: getSellerProfileUrl(listing.sellerId),
                className: styles$b.sellerLink,
                target: "_blank",
                rel: "noopener noreferrer",
                children: formatSellerId(listing.sellerId)
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              CopyIdButton,
              {
                id: listing.sellerId,
                label: "Copy target ID",
                copiedLabel: "Copied"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: verifiedLabel }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$b.rowValue, children: [
            verified,
            "/",
            quantity2
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$b.row} tlm-payout-hover-scope`, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: payPerLabel }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PayoutValue,
            {
              amount: listing.payPerLoss,
              conversion: payoutConversion,
              label: payPerLabel,
              className: styles$b.rowValuePay
            }
          )
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$b.row} tlm-payout-hover-scope`, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Pay" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PayoutValue,
            {
              amount: totalPayout,
              conversion: payoutConversion,
              label: "Total payout",
              className: styles$b.rowValuePay
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ContractCompleteActions, { onClose })
    ] });
  }
  function AnimatedItem({
    children,
    delay: delay2 = 0,
    index,
    onMouseEnter,
    onClick,
    dense = false,
    disableEntranceAnimation = false
  }) {
    const ref = reactExports.useRef(null);
    const inView2 = useInView(ref, { amount: 0.5 });
    const visible = disableEntranceAnimation || inView2;
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      motion.div,
      {
        ref,
        "data-index": index,
        onMouseEnter,
        onClick,
        initial: { scale: 0.7, opacity: 0 },
        animate: visible ? { scale: 1, opacity: 1 } : { scale: 0.7, opacity: 0 },
        transition: { duration: 0.2, delay: delay2 },
        style: {
          marginBottom: dense ? 0 : "0.75rem",
          cursor: "pointer"
        },
        children
      }
    );
  }
  function AnimatedList({
    items,
    renderItem,
    getItemKey,
    onItemSelect,
    showGradients = true,
    enableArrowNavigation = true,
    className = "",
    itemClassName = "",
    displayScrollbar = true,
    initialSelectedIndex = -1,
    dense = false,
    listAriaLabel = "Listings",
    selectOnHover = true,
    disableEntranceAnimation = false
  }) {
    const listRef = reactExports.useRef(null);
    const [selectedIndex, setSelectedIndex] = reactExports.useState(initialSelectedIndex);
    const [keyboardNav, setKeyboardNav] = reactExports.useState(false);
    const [topGradientOpacity, setTopGradientOpacity] = reactExports.useState(0);
    const [bottomGradientOpacity, setBottomGradientOpacity] = reactExports.useState(1);
    reactExports.useEffect(() => {
      setSelectedIndex(initialSelectedIndex);
    }, [items, initialSelectedIndex]);
    const handleItemMouseEnter = reactExports.useCallback((index) => {
      setSelectedIndex(index);
    }, []);
    const handleItemClick = reactExports.useCallback(
      (item, index) => {
        setSelectedIndex(index);
        onItemSelect == null ? void 0 : onItemSelect(item, index);
      },
      [onItemSelect]
    );
    const handleScroll = reactExports.useCallback((e) => {
      const target2 = e.target;
      const { scrollTop, scrollHeight, clientHeight } = target2;
      setTopGradientOpacity(Math.min(scrollTop / 50, 1));
      const bottomDistance = scrollHeight - (scrollTop + clientHeight);
      setBottomGradientOpacity(
        scrollHeight <= clientHeight ? 0 : Math.min(bottomDistance / 50, 1)
      );
    }, []);
    const handleKeyDown = reactExports.useCallback(
      (e) => {
        if (!enableArrowNavigation) return;
        if (e.key === "ArrowDown" || e.key === "Tab" && !e.shiftKey) {
          e.preventDefault();
          setKeyboardNav(true);
          setSelectedIndex((prev) => Math.min(prev + 1, items.length - 1));
        } else if (e.key === "ArrowUp" || e.key === "Tab" && e.shiftKey) {
          e.preventDefault();
          setKeyboardNav(true);
          setSelectedIndex((prev) => Math.max(prev - 1, 0));
        } else if (e.key === "Enter" && selectedIndex >= 0) {
          e.preventDefault();
          onItemSelect == null ? void 0 : onItemSelect(items[selectedIndex], selectedIndex);
        }
      },
      [enableArrowNavigation, items, onItemSelect, selectedIndex]
    );
    reactExports.useEffect(() => {
      if (!keyboardNav || selectedIndex < 0 || !listRef.current) return;
      const container = listRef.current;
      const selectedItem = container.querySelector(
        `[data-index="${selectedIndex}"]`
      );
      if (!selectedItem) return;
      const extraMargin = 50;
      const containerScrollTop = container.scrollTop;
      const containerHeight = container.clientHeight;
      const itemTop = selectedItem.offsetTop;
      const itemBottom = itemTop + selectedItem.offsetHeight;
      if (itemTop < containerScrollTop + extraMargin) {
        container.scrollTo({ top: itemTop - extraMargin, behavior: "smooth" });
      } else if (itemBottom > containerScrollTop + containerHeight - extraMargin) {
        container.scrollTo({
          top: itemBottom - containerHeight + extraMargin,
          behavior: "smooth"
        });
      }
      setKeyboardNav(false);
    }, [selectedIndex, keyboardNav]);
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `scroll-list-container ${className}`, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          ref: listRef,
          className: `scroll-list ${!displayScrollbar ? "no-scrollbar" : ""}`,
          onScroll: handleScroll,
          onKeyDown: handleKeyDown,
          tabIndex: 0,
          role: "listbox",
          "aria-label": listAriaLabel,
          children: items.map((item, index) => /* @__PURE__ */ jsxRuntimeExports.jsx(
            AnimatedItem,
            {
              delay: 0.05,
              index,
              dense,
              disableEntranceAnimation,
              onMouseEnter: selectOnHover ? () => handleItemMouseEnter(index) : void 0,
              onClick: () => handleItemClick(item, index),
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: `item ${selectedIndex === index ? "selected" : ""} ${itemClassName}`,
                  role: "option",
                  "aria-selected": selectedIndex === index,
                  children: renderItem ? renderItem(item, index) : /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "item-text", children: String(item) })
                }
              )
            },
            (getItemKey == null ? void 0 : getItemKey(item, index)) ?? index
          ))
        }
      ),
      showGradients && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: "top-gradient",
            style: { opacity: topGradientOpacity }
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            className: "bottom-gradient",
            style: { opacity: bottomGradientOpacity }
          }
        )
      ] })
    ] });
  }
  const panel$2 = "_panel_15vqv_1";
  const typePickerBar = "_typePickerBar_15vqv_8";
  const pickerRowMain = "_pickerRowMain_15vqv_19";
  const tableEmpty = "_tableEmpty_15vqv_24";
  const tableEmptyState = "_tableEmptyState_15vqv_33";
  const setAlertButton = "_setAlertButton_15vqv_41";
  const tableComingSoon = "_tableComingSoon_15vqv_75";
  const tableProductivityBoost = "_tableProductivityBoost_15vqv_85";
  const tableHeaderRow = "_tableHeaderRow_15vqv_85";
  const rowCells = "_rowCells_15vqv_86";
  const columnHeader = "_columnHeader_15vqv_90";
  const cellPay = "_cellPay_15vqv_91";
  const table = "_table_15vqv_24";
  const tableHead = "_tableHead_15vqv_85";
  const columnHeaderActive = "_columnHeaderActive_15vqv_150";
  const sortIdle = "_sortIdle_15vqv_155";
  const sortActive = "_sortActive_15vqv_161";
  const tableBody = "_tableBody_15vqv_167";
  const list$3 = "_list_15vqv_174";
  const tableRow = "_tableRow_15vqv_204";
  const tableRowSelectable = "_tableRowSelectable_15vqv_221";
  const cell = "_cell_15vqv_91";
  const cellQuantity = "_cellQuantity_15vqv_236";
  const tableBounties = "_tableBounties_15vqv_242";
  const bountyColumnHeaderQuantity = "_bountyColumnHeaderQuantity_15vqv_248";
  const bountyCellQuantity = "_bountyCellQuantity_15vqv_253";
  const cellSeller = "_cellSeller_15vqv_258";
  const sellerLink = "_sellerLink_15vqv_262";
  const takeContractBtn = "_takeContractBtn_15vqv_287";
  const takeContractBtnRevealed = "_takeContractBtnRevealed_15vqv_327";
  const tableRowOwn = "_tableRowOwn_15vqv_356";
  const cancelRedeem = "_cancelRedeem_15vqv_356";
  const tableRowHighlighted = "_tableRowHighlighted_15vqv_361";
  const tableRowReserved = "_tableRowReserved_15vqv_416";
  const fullyReservedBadge = "_fullyReservedBadge_15vqv_425";
  const webSellNotice = "_webSellNotice_15vqv_444";
  const webSellNoticeTitle = "_webSellNoticeTitle_15vqv_458";
  const styles$9 = {
    panel: panel$2,
    typePickerBar,
    pickerRowMain,
    tableEmpty,
    tableEmptyState,
    setAlertButton,
    tableComingSoon,
    tableProductivityBoost,
    tableHeaderRow,
    rowCells,
    columnHeader,
    cellPay,
    table,
    tableHead,
    columnHeaderActive,
    sortIdle,
    sortActive,
    tableBody,
    list: list$3,
    tableRow,
    tableRowSelectable,
    cell,
    cellQuantity,
    tableBounties,
    bountyColumnHeaderQuantity,
    bountyCellQuantity,
    cellSeller,
    sellerLink,
    takeContractBtn,
    takeContractBtnRevealed,
    tableRowOwn,
    cancelRedeem,
    tableRowHighlighted,
    tableRowReserved,
    fullyReservedBadge,
    webSellNotice,
    webSellNoticeTitle
  };
  function MarketListingsEmptyState({
    message,
    onSetAlert,
    alertThreshold = null,
    formatAlertThreshold
  }) {
    const alertLabel = alertThreshold !== null && formatAlertThreshold ? `Alert set at: ${formatAlertThreshold(alertThreshold)}` : "Set Alert?";
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.tableEmptyState, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$9.tableEmpty, children: message }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          className: styles$9.setAlertButton,
          onClick: onSetAlert,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Bell, { size: 14, strokeWidth: 2, "aria-hidden": true }),
            alertLabel
          ]
        }
      )
    ] });
  }
  function thresholdToInput(value) {
    if (value === null) return "";
    return value.toLocaleString("en-US");
  }
  function getPriceAlertValidationMessage(raw, singular) {
    const trimmed = raw.trim();
    if (!trimmed) return null;
    const value = evaluateNumericInput(trimmed);
    if (value === null) {
      return `Enter a valid price (${formatExtensionPoints(BUYER_ORDER_PRICE_MIN)}–${formatExtensionPoints(BUYER_ORDER_PRICE_MAX)}, optional k/m/b).`;
    }
    if (!Number.isInteger(value)) {
      return "Price must be a whole number (e.g. 100k or 0.4m).";
    }
    if (value < BUYER_ORDER_PRICE_MIN) {
      return `Price per ${singular} must be at least ${formatExtensionPoints(BUYER_ORDER_PRICE_MIN)}.`;
    }
    if (value > BUYER_ORDER_PRICE_MAX) {
      return `Price per ${singular} cannot exceed ${formatExtensionPoints(BUYER_ORDER_PRICE_MAX)}.`;
    }
    return null;
  }
  function getPayAlertValidationMessage(raw, contractType) {
    return getPriceAlertValidationMessage(
      raw,
      CONTRACT_TYPE_SINGULAR[contractType].toLowerCase()
    );
  }
  function getQuantityAlertValidationMessage(raw, label2) {
    const trimmed = raw.trim();
    if (!trimmed) return null;
    const value = evaluateNumericInput(trimmed);
    if (value === null) {
      return `Enter a valid quantity (${ALERT_WITHDRAWAL_QTY_MIN}–${ALERT_WITHDRAWAL_QTY_MAX.toLocaleString("en-US")}, optional k/m/b).`;
    }
    if (!Number.isInteger(value)) {
      return "Quantity must be a whole number.";
    }
    if (value < ALERT_WITHDRAWAL_QTY_MIN) {
      return `${label2} quantity must be at least ${ALERT_WITHDRAWAL_QTY_MIN.toLocaleString("en-US")}.`;
    }
    if (value > ALERT_WITHDRAWAL_QTY_MAX) {
      return `${label2} quantity cannot exceed ${ALERT_WITHDRAWAL_QTY_MAX.toLocaleString("en-US")}.`;
    }
    return null;
  }
  const wrap$1 = "_wrap_1vlbk_1";
  const bell$1 = "_bell_1vlbk_7";
  const bellActive = "_bellActive_1vlbk_45";
  const matchBadge = "_matchBadge_1vlbk_51";
  const popover = "_popover_1vlbk_79";
  const title$2 = "_title_1vlbk_97";
  const inputWrap = "_inputWrap_1vlbk_105";
  const input$1 = "_input_1vlbk_105";
  const inputError = "_inputError_1vlbk_157";
  const note = "_note_1vlbk_161";
  const error$1 = "_error_1vlbk_168";
  const saved = "_saved_1vlbk_175";
  const actions$2 = "_actions_1vlbk_183";
  const save = "_save_1vlbk_175";
  const clearBtn = "_clearBtn_1vlbk_212";
  const hint = "_hint_1vlbk_239";
  const styles$8 = {
    wrap: wrap$1,
    bell: bell$1,
    bellActive,
    matchBadge,
    popover,
    title: title$2,
    inputWrap,
    input: input$1,
    inputError,
    note,
    error: error$1,
    saved,
    actions: actions$2,
    save,
    clearBtn,
    hint
  };
  const STATUS_CLEAR_MS = 1600;
  function AlertBellPopover({
    label: label2,
    kind,
    value,
    onCommit,
    disabled = false,
    open,
    onOpenChange,
    singular,
    className,
    size = 34,
    balance,
    matchingCount
  }) {
    const wrapRef = reactExports.useRef(null);
    const inputRef = reactExports.useRef(null);
    const inputId = reactExports.useId();
    const [input2, setInput] = reactExports.useState(() => thresholdToInput(value));
    const [error2, setError] = reactExports.useState(null);
    const [status2, setStatus] = reactExports.useState(null);
    const statusTimer = reactExports.useRef(null);
    const active = value !== null;
    const priceNoun = singular ?? label2.toLowerCase();
    const tracksMatches = matchingCount !== void 0;
    const highlighted = tracksMatches ? matchingCount > 0 : active;
    const showBadge = tracksMatches && matchingCount > 0;
    reactExports.useEffect(() => {
      if (!open) {
        setInput(thresholdToInput(value));
        setError(null);
      }
    }, [value, open]);
    reactExports.useEffect(() => {
      if (open) {
        setInput(thresholdToInput(value));
        setError(null);
        setStatus(null);
        const id2 = requestAnimationFrame(() => {
          var _a2;
          return (_a2 = inputRef.current) == null ? void 0 : _a2.focus();
        });
        return () => cancelAnimationFrame(id2);
      }
      return void 0;
    }, [open, value]);
    reactExports.useEffect(() => {
      if (!open) return void 0;
      const handlePointerDown = (event) => {
        const path = event.composedPath();
        if (!path.includes(wrapRef.current)) {
          onOpenChange(false);
        }
      };
      document.addEventListener("mousedown", handlePointerDown);
      return () => document.removeEventListener("mousedown", handlePointerDown);
    }, [open, onOpenChange]);
    reactExports.useEffect(
      () => () => {
        if (statusTimer.current) clearTimeout(statusTimer.current);
      },
      []
    );
    const flashStatus = (next) => {
      setStatus(next);
      if (statusTimer.current) clearTimeout(statusTimer.current);
      statusTimer.current = setTimeout(() => setStatus(null), STATUS_CLEAR_MS);
    };
    const clear = () => {
      setInput("");
      setError(null);
      onCommit(null);
      flashStatus("cleared");
    };
    const commit = (overrideRaw) => {
      const raw = overrideRaw ?? input2;
      const trimmed = raw.trim();
      if (!trimmed) {
        clear();
        return;
      }
      if (evaluateNumericInput(trimmed) === 0) {
        clear();
        return;
      }
      const message = kind === "price" ? getPriceAlertValidationMessage(raw, priceNoun) : getQuantityAlertValidationMessage(raw, label2);
      if (message) {
        setError(message);
        return;
      }
      const parsed = kind === "price" ? parsePriceInput(raw) : parseQuantityInput(raw);
      if (parsed === null) {
        setError(
          kind === "price" ? "Enter a valid price (optional k/m/b)." : "Enter a valid quantity (optional k/m/b)."
        );
        return;
      }
      setError(null);
      setInput(thresholdToInput(parsed));
      onCommit(parsed);
      flashStatus("saved");
    };
    const toggle = () => {
      if (disabled) return;
      onOpenChange(!open);
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { ref: wrapRef, className: `${styles$8.wrap} ${className ?? ""}`, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          className: `${styles$8.bell} ${highlighted ? styles$8.bellActive : ""}`,
          style: { width: size, height: size },
          onClick: toggle,
          disabled,
          "aria-haspopup": "dialog",
          "aria-expanded": open,
          "aria-label": active ? `Edit ${label2} alert` : `Set ${label2} alert`,
          title: active ? `Edit ${label2} alert` : `Set ${label2} alert`,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Bell,
              {
                size: 16,
                strokeWidth: 2,
                "aria-hidden": true,
                ...highlighted ? { fill: "currentColor" } : {}
              }
            ),
            showBadge && /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$8.matchBadge, "aria-hidden": true, children: matchingCount > 9 ? "9+" : matchingCount })
          ]
        }
      ),
      open && /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: styles$8.popover,
          role: "dialog",
          "aria-label": `${label2} alert`,
          onKeyDown: (e) => {
            if (e.key === "Escape") {
              e.preventDefault();
              onOpenChange(false);
            }
          },
          children: disabled ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$8.hint, children: "Connect your API key to save alert settings." }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: styles$8.title, htmlFor: inputId, children: [
              "Alert me on ",
              label2.toLowerCase(),
              " at or above"
            ] }),
            kind === "price" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              PtsAmountInput,
              {
                id: inputId,
                inputRef,
                value: input2,
                onChange: (next) => {
                  setInput(next);
                  setError(null);
                  setStatus(null);
                },
                onEnter: (committed) => commit(committed),
                max: BUYER_ORDER_PRICE_MAX,
                referenceMax: balance,
                sanitize: sanitizePriceInput,
                inputMode: "decimal",
                placeholder: "Pay",
                ariaLabel: `${label2} alert threshold`,
                hasError: Boolean(error2)
              }
            ) : /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$8.inputWrap, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              "input",
              {
                id: inputId,
                ref: inputRef,
                className: `${styles$8.input} ${error2 ? styles$8.inputError : ""}`,
                type: "text",
                inputMode: "numeric",
                placeholder: "Quantity",
                value: input2,
                "aria-label": `${label2} alert threshold`,
                onChange: (e) => {
                  setInput(sanitizeQuantityInput(e.target.value));
                  setError(null);
                  setStatus(null);
                },
                onKeyDown: (e) => {
                  if (e.key === "Enter") {
                    e.preventDefault();
                    commit();
                  }
                }
              }
            ) }),
            error2 ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$8.error, role: "alert", children: error2 }) : status2 ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$8.saved, "aria-live": "polite", children: status2 === "saved" ? "Saved…" : "Cleared" }) : /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$8.note, children: "We'll flash the panel and play a sound when a match appears." }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$8.actions, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  className: styles$8.save,
                  onClick: () => commit(),
                  children: "Save"
                }
              ),
              active && /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  className: styles$8.clearBtn,
                  onClick: clear,
                  children: "Clear"
                }
              )
            ] })
          ] })
        }
      )
    ] });
  }
  function SortIndicator$1({
    active,
    descending
  }) {
    if (!active) return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$9.sortIdle, "aria-hidden": "true" });
    return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$9.sortActive, "aria-hidden": "true", children: descending ? "↓" : "↑" });
  }
  function BuyingPanel({
    balance,
    listings,
    onListingSelect,
    onCancelOwnListing,
    showLossContractPanel,
    showLossCompletedPanel,
    displayLossContract,
    completedLossContract,
    contractSecondsRemaining,
    onDismissCompletedLoss,
    highlightedListingId,
    ownListingIds,
    currentUserXid,
    onTurnInContract,
    lossTurnInState,
    lossTurnInError,
    payoutConversion,
    tornXid,
    sessionLoading = false,
    contractTypeAlertHighlights,
    alertThreshold = null,
    alertEscapeThreshold = null,
    alertStalemateThreshold = null,
    onAlertThresholdChange = () => {
    },
    onAlertEscapeThresholdChange = () => {
    },
    onAlertStalemateThresholdChange = () => {
    },
    onOpenSettings,
    navRequest,
    takeContractTutorialTargetId = null,
    takeContractTutorialRef
  }) {
    const [alertOpen, setAlertOpen] = reactExports.useState(false);
    const [contractType, setContractType] = reactExports.useState(() => {
      if (sessionLoading) return null;
      return readStoredSellContractTypeSync(tornXid) ?? "losses";
    });
    const [sortField, setSortField] = reactExports.useState("payPerLoss");
    const [sortDescending, setSortDescending] = reactExports.useState(true);
    const navOverrideRef = reactExports.useRef(false);
    reactExports.useEffect(() => {
      if (sessionLoading) return;
      navOverrideRef.current = false;
      const cached = readStoredSellContractTypeSync(tornXid) ?? "losses";
      setContractType(cached);
      let cancelled = false;
      void loadSellContractType(tornXid).then((stored) => {
        if (!cancelled && !navOverrideRef.current) setContractType(stored);
      });
      return () => {
        cancelled = true;
      };
    }, [tornXid, sessionLoading]);
    const handleContractTypeChange = (next) => {
      setContractType(next);
      void saveSellContractType(tornXid, next);
    };
    const navToken = navRequest == null ? void 0 : navRequest.token;
    reactExports.useEffect(() => {
      if (!navRequest) return;
      navOverrideRef.current = true;
      handleContractTypeChange(navRequest.contractType);
    }, [navToken]);
    reactExports.useEffect(() => {
      if (!takeContractTutorialTargetId || !takeContractTutorialRef) return;
      const id2 = requestAnimationFrame(() => {
        var _a2;
        if (typeof takeContractTutorialRef === "object" && takeContractTutorialRef !== null && "current" in takeContractTutorialRef) {
          (_a2 = takeContractTutorialRef.current) == null ? void 0 : _a2.scrollIntoView({ block: "nearest" });
        }
      });
      return () => cancelAnimationFrame(id2);
    }, [takeContractTutorialTargetId, takeContractTutorialRef]);
    const activeContractType = contractType ?? "losses";
    const listingContractType = activeContractType;
    const contractLabel = CONTRACT_TYPE_LABELS[listingContractType];
    const contractSingular = CONTRACT_TYPE_SINGULAR[listingContractType].toLowerCase();
    const contractPlural = contractLabel.toLowerCase();
    const displayListings = listings.filter(
      (listing) => listing.contractType === listingContractType
    );
    const columns = [
      { field: "sellerId", label: "Targets" },
      { field: "quantity", label: "Quantity" },
      { field: "payPerLoss", label: getPayPerLabel(listingContractType) }
    ];
    const sortedListings = reactExports.useMemo(
      () => sortListings(displayListings, sortField, sortDescending),
      [displayListings, sortField, sortDescending]
    );
    const activeAlertThreshold = listingContractType === "losses" ? alertThreshold : listingContractType === "escapes" ? alertEscapeThreshold : alertStalemateThreshold;
    const activeAlertOnChange = listingContractType === "losses" ? onAlertThresholdChange : listingContractType === "escapes" ? onAlertEscapeThresholdChange : onAlertStalemateThresholdChange;
    const handleHeaderClick = (field2) => {
      if (field2 === sortField) {
        setSortDescending((d) => !d);
      } else {
        setSortField(field2);
        setSortDescending(true);
      }
    };
    if (showLossContractPanel && displayLossContract) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        ActiveContractPanel,
        {
          contract: displayLossContract,
          secondsRemaining: contractSecondsRemaining,
          onTurnIn: onTurnInContract,
          turnInState: lossTurnInState,
          turnInError: lossTurnInError,
          payoutConversion
        }
      );
    }
    if (showLossCompletedPanel && completedLossContract) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        CompletedContractPanel,
        {
          contract: completedLossContract,
          onClose: onDismissCompletedLoss,
          payoutConversion
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        className: styles$9.panel,
        role: "region",
        "aria-label": `Sell ${contractLabel.toLowerCase()}`,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.typePickerBar, children: !sessionLoading && contractType !== null && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.pickerRowMain, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              ContractTypePicker,
              {
                variant: "segment",
                value: contractType,
                onChange: handleContractTypeChange,
                "aria-label": "Contract type to sell",
                alertHighlightedTypes: contractTypeAlertHighlights
              }
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              AlertBellPopover,
              {
                label: contractLabel,
                kind: "price",
                singular: contractSingular,
                value: activeAlertThreshold,
                onCommit: activeAlertOnChange,
                balance,
                disabled: tornXid === null,
                open: alertOpen,
                onOpenChange: setAlertOpen,
                size: 44
              }
            )
          ] }) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.table, role: "table", children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHead, role: "rowgroup", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHeaderRow, role: "row", children: columns.map(({ field: field2, label: label2 }) => {
              const active = sortField === field2;
              return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "button",
                {
                  type: "button",
                  role: "columnheader",
                  "aria-sort": active ? sortDescending ? "descending" : "ascending" : "none",
                  className: `${styles$9.columnHeader} ${active ? styles$9.columnHeaderActive : ""}`,
                  onClick: () => handleHeaderClick(field2),
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: label2 }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(SortIndicator$1, { active, descending: sortDescending })
                  ]
                },
                field2
              );
            }) }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableBody, role: "rowgroup", children: sortedListings.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              MarketListingsEmptyState,
              {
                message: listingContractType === "losses" ? "No loss listings right now." : `No ${contractPlural} listings yet.`,
                onSetAlert: tornXid === null ? onOpenSettings : () => setAlertOpen(true),
                alertThreshold: activeAlertThreshold,
                formatAlertThreshold: formatExtensionPoints
              }
            ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
              AnimatedList,
              {
                className: styles$9.list,
                itemClassName: "tlm-table-row-item",
                selectOnHover: false,
                disableEntranceAnimation: takeContractTutorialTargetId != null,
                items: sortedListings,
                getItemKey: (item) => item.id,
                showGradients: true,
                enableArrowNavigation: true,
                displayScrollbar: true,
                dense: true,
                listAriaLabel: `${contractLabel} listings`,
                onItemSelect: (listing) => {
                  const isOwn = ownListingIds.has(listing.id) || listing.sellerId === currentUserXid;
                  const isReserved = listing.quantity === 0;
                  if (isOwn || isReserved) return;
                  onListingSelect(listing);
                },
                renderItem: (listing) => {
                  const isHighlighted = listing.id === highlightedListingId;
                  const isOwn = ownListingIds.has(listing.id) || listing.sellerId === currentUserXid;
                  const isReserved = listing.quantity === 0;
                  const isSelectable = !isOwn && !isReserved;
                  const takeContract = () => onListingSelect(listing);
                  const rowLabel2 = isOwn ? `Your buy order, ${listing.quantity} ${contractPlural}, ${formatExtensionPoints(listing.payPerLoss)} per ${contractSingular}` : isReserved ? `Buyer ${formatSellerId(listing.sellerId)}, fully reserved at ${formatExtensionPoints(listing.payPerLoss)} per ${contractSingular}` : `Buyer ${formatSellerId(listing.sellerId)}, ${listing.quantity} ${contractPlural}, ${formatExtensionPoints(listing.payPerLoss)} per ${contractSingular} — ${takeContractRowHint()}`;
                  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "div",
                    {
                      className: [
                        styles$9.tableRow,
                        "tlm-payout-hover-scope",
                        isSelectable ? styles$9.tableRowSelectable : "",
                        isHighlighted ? styles$9.tableRowHighlighted : "",
                        isOwn && !isHighlighted ? styles$9.tableRowOwn : "",
                        isReserved && !isOwn ? styles$9.tableRowReserved : ""
                      ].filter(Boolean).join(" "),
                      role: "row",
                      "aria-label": rowLabel2,
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.rowCells, children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellSeller}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "a",
                            {
                              href: getSellerProfileUrl(listing.sellerId),
                              className: styles$9.sellerLink,
                              ...externalLinkProps(),
                              onClick: (e) => e.stopPropagation(),
                              children: formatSellerId(listing.sellerId)
                            }
                          ) }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellQuantity}`, children: isReserved && !isOwn ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$9.fullyReservedBadge, children: "Fully reserved" }) : listing.quantity.toLocaleString("en-US") }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellPay}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                            PayoutValue,
                            {
                              amount: listing.payPerLoss,
                              conversion: payoutConversion,
                              label: `Pay per ${contractSingular}`
                            }
                          ) })
                        ] }),
                        isSelectable && /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "button",
                          {
                            type: "button",
                            className: `${styles$9.takeContractBtn} ${listing.id === takeContractTutorialTargetId ? styles$9.takeContractBtnRevealed : ""}`,
                            ref: listing.id === takeContractTutorialTargetId ? takeContractTutorialRef : void 0,
                            onClick: (e) => {
                              e.stopPropagation();
                              takeContract();
                            },
                            children: TAKE_CONTRACT_BUTTON_LABEL
                          }
                        ),
                        isOwn && !isReserved && /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "button",
                          {
                            type: "button",
                            className: styles$9.cancelRedeem,
                            "aria-label": "Cancel buy order and refund remaining balance",
                            onClick: (e) => {
                              e.stopPropagation();
                              onCancelOwnListing(listing.id);
                            },
                            children: "×"
                          }
                        )
                      ]
                    }
                  );
                }
              }
            ) })
          ] })
        ]
      }
    );
  }
  const SERVICE_TYPES = [
    "withdrawals",
    "bounties",
    "other"
  ];
  const SERVICE_TYPE_LABELS = {
    withdrawals: "Withdrawals",
    bounties: "Bounties",
    other: "Other"
  };
  function isServiceType(value) {
    return SERVICE_TYPES.includes(value);
  }
  const SERVICES_KEY_PREFIX = "service_type_";
  function servicesKey(tornXid) {
    return tornXid == null ? `${SERVICES_KEY_PREFIX}guest` : `${SERVICES_KEY_PREFIX}${tornXid}`;
  }
  function syncKey(tornXid) {
    return servicesKey(tornXid);
  }
  function readSync$1(tornXid) {
    try {
      const raw = readLocalStorageWithMigration(localStorage, syncKey(tornXid));
      if (typeof raw === "string" && isServiceType(raw)) return raw;
    } catch {
    }
    return null;
  }
  function writeSync$1(tornXid, type) {
    try {
      writeLocalStorageCurrent(localStorage, syncKey(tornXid), type);
    } catch {
    }
  }
  function readStoredServiceTypeSync(tornXid) {
    return readSync$1(tornXid);
  }
  async function loadServiceType(tornXid) {
    const key = servicesKey(tornXid);
    try {
      const raw = await getPlatformRuntime().storage.get(key);
      if (typeof raw === "string" && isServiceType(raw)) {
        writeSync$1(tornXid, raw);
        return raw;
      }
    } catch {
    }
    const cached = readSync$1(tornXid);
    if (cached != null) return cached;
    return "withdrawals";
  }
  async function saveServiceType(tornXid, type) {
    writeSync$1(tornXid, type);
    const key = servicesKey(tornXid);
    try {
      await getPlatformRuntime().storage.set(key, type);
    } catch {
    }
  }
  function ActiveBountyFulfillmentPanel({
    fulfillment,
    secondsRemaining,
    onTurnIn,
    turnInState,
    turnInError: turnInError2,
    payoutConversion
  }) {
    var _a2;
    const { order, targetId, slotsTotal, slotsRemaining, slotsVerified } = fulfillment;
    const total = slotsTotal ?? 0;
    const verified = Math.min(slotsVerified ?? 0, total);
    const remaining = Math.min(
      slotsRemaining ?? Math.max(0, total - verified),
      total
    );
    const averageXanaxPrice = ((_a2 = payoutConversion.price) == null ? void 0 : _a2.averagePrice) ?? null;
    const perSlotPayPts = computeBountyPerContractPts(
      order.bountyValueTorn,
      averageXanaxPrice,
      convertTornDollarsToScriptPoints
    ).totalPts;
    const totalPayPts = perSlotPayPts != null ? perSlotPayPts * total : null;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.panel, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$b.badge, children: "Active contract" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$b.timer, children: formatCountdown(secondsRemaining) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$b.timerHint, children: "remaining to place bounty" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.details, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Target" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.partyValue, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "a",
              {
                href: getTornProfileUrl(targetId),
                className: styles$b.sellerLink,
                target: "_blank",
                rel: "noopener noreferrer",
                children: String(targetId)
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              CopyIdButton,
              {
                id: targetId,
                label: "Copy target ID",
                copiedLabel: "Copied"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Bounty value" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowValue, children: formatMoney(order.bountyValueTorn) })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Bounties placed" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$b.rowValue, children: [
            verified.toLocaleString("en-US"),
            "/",
            total.toLocaleString("en-US")
          ] })
        ] }),
        remaining > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Still to place" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowValue, children: remaining.toLocaleString("en-US") })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$b.row} tlm-payout-hover-scope`, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Pay / Slot" }),
          perSlotPayPts != null ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            PayoutValue,
            {
              amount: perSlotPayPts,
              conversion: payoutConversion,
              label: "Bounty fulfillment pay per slot",
              className: styles$b.rowValuePay
            }
          ) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowValue, children: "—" })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$b.row} tlm-payout-hover-scope`, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Pay" }),
          totalPayPts != null ? /* @__PURE__ */ jsxRuntimeExports.jsx(
            PayoutValue,
            {
              amount: totalPayPts,
              conversion: payoutConversion,
              label: "Bounty fulfillment total pay",
              className: styles$b.rowValuePay
            }
          ) : /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowValue, children: "—" })
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        ContractTurnInActions,
        {
          shortcutLabel: "Bounty",
          shortcutHref: getTornBountyAddUrl(targetId),
          onTurnIn,
          turnInState,
          turnInError: turnInError2
        }
      )
    ] });
  }
  function ActiveEmbargoFulfillmentPanel({
    embargo,
    secondsRemaining,
    onTurnIn,
    turnInState,
    turnInError: turnInError2,
    payoutConversion
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.panel, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$b.badge, children: "Active contract" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$b.timer, children: formatCountdown(secondsRemaining) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$b.timerHint, children: "remaining to embargo target" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.details, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Target" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.partyValue, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(EmbargoTargetLink, { targetUserId: embargo.targetUserId }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              CopyIdButton,
              {
                id: embargo.targetUserId,
                label: "Copy target ID",
                copiedLabel: "Copied"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$b.row} tlm-payout-hover-scope`, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Pay" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PayoutValue,
            {
              amount: embargo.escrowedPts,
              conversion: payoutConversion,
              label: "Embargo payout",
              className: styles$b.rowValuePay
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        ContractTurnInActions,
        {
          shortcutLabel: "Embargo",
          shortcutHref: COMPANIES_SPECIAL_URL,
          onTurnIn,
          turnInState,
          turnInError: turnInError2
        }
      )
    ] });
  }
  function ActiveFlightDelayFulfillmentPanel({
    flightDelay,
    secondsRemaining,
    onTurnIn,
    turnInState,
    turnInError: turnInError2,
    payoutConversion
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.panel, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$b.badge, children: "Active contract" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$b.timer, children: formatCountdown(secondsRemaining) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$b.timerHint, children: "remaining to delay target" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.details, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Target" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.partyValue, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(FlightDelayTargetLink, { targetUserId: flightDelay.targetUserId }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              CopyIdButton,
              {
                id: flightDelay.targetUserId,
                label: "Copy target ID",
                copiedLabel: "Copied"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$b.row} tlm-payout-hover-scope`, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Pay" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PayoutValue,
            {
              amount: flightDelay.escrowedPts,
              conversion: payoutConversion,
              label: "Flight delay payout",
              className: styles$b.rowValuePay
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        ContractTurnInActions,
        {
          shortcutLabel: "Delay",
          shortcutHref: COMPANIES_SPECIAL_URL,
          onTurnIn,
          turnInState,
          turnInError: turnInError2
        }
      )
    ] });
  }
  function ActiveSimpleServiceFulfillmentPanel({
    config,
    service,
    secondsRemaining,
    onTurnIn,
    turnInState,
    turnInError: turnInError2,
    payoutConversion
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.panel, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$b.badge, children: "Active contract" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$b.timer, children: formatCountdown(secondsRemaining) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: styles$b.timerHint, children: [
        "remaining to fulfill ",
        config.label.toLowerCase()
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.details, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Target" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.partyValue, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(SimpleServiceTargetLink, { targetUserId: service.targetUserId }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              CopyIdButton,
              {
                id: service.targetUserId,
                label: "Copy target ID",
                copiedLabel: "Copied"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$b.row} tlm-payout-hover-scope`, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Pay" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PayoutValue,
            {
              amount: service.escrowedPts,
              conversion: payoutConversion,
              label: `${config.label} payout`,
              className: styles$b.rowValuePay
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        ContractTurnInActions,
        {
          shortcutLabel: "Special",
          shortcutHref: COMPANIES_SPECIAL_URL,
          onTurnIn,
          turnInState,
          turnInError: turnInError2
        }
      )
    ] });
  }
  function ActiveProductivityBoostFulfillmentPanel({
    boost,
    secondsRemaining,
    onTurnIn,
    turnInState,
    turnInError: turnInError2,
    payoutConversion
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.panel, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$b.badge, children: "Active contract" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$b.timer, children: formatCountdown(secondsRemaining) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$b.timerHint, children: "remaining to boost productivity" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.details, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Company" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.partyValue, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(ProductivityBoostCompanyLink, { companyId: boost.companyId }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              CopyIdButton,
              {
                id: boost.companyId,
                label: "Copy company ID",
                copiedLabel: "Copied"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$b.row} tlm-payout-hover-scope`, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Pay" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PayoutValue,
            {
              amount: boost.escrowedPts,
              conversion: payoutConversion,
              label: "Productivity boost payout",
              className: styles$b.rowValuePay
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        ContractTurnInActions,
        {
          shortcutLabel: "Special",
          shortcutHref: COMPANIES_SPECIAL_URL,
          onTurnIn,
          turnInState,
          turnInError: turnInError2
        }
      )
    ] });
  }
  function ActiveRedeemingFulfillmentPanel({
    fulfillment,
    secondsRemaining,
    onTurnIn,
    turnInState,
    turnInError: turnInError2,
    payoutConversion
  }) {
    const { listing, xanaxRemaining, xanaxTotal, xanaxVerified } = fulfillment;
    const total = xanaxTotal ?? 0;
    const verified = Math.min(xanaxVerified ?? 0, total);
    const remaining = Math.min(xanaxRemaining ?? Math.max(0, total - verified), total);
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.panel, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$b.badge, children: "Active contract" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$b.timer, children: formatCountdown(secondsRemaining) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$b.timerHint, children: "remaining to send Xanax" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.details, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Requester" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.partyValue, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "a",
              {
                href: getRequesterProfileUrl(listing.requesterId),
                className: styles$b.sellerLink,
                target: "_blank",
                rel: "noopener noreferrer",
                children: formatRequesterId(listing.requesterId)
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              CopyIdButton,
              {
                id: listing.requesterId,
                label: "Copy requester ID",
                copiedLabel: "Copied"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Xanax sent" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$b.rowValue, children: [
            verified.toLocaleString("en-US"),
            "/",
            total.toLocaleString("en-US")
          ] })
        ] }),
        remaining > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Still to send" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowValue, children: remaining.toLocaleString("en-US") })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$b.row} tlm-payout-hover-scope`, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Pay" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PayoutValue,
            {
              amount: getRedeemingPayAmount(total),
              conversion: payoutConversion,
              label: "Withdrawal payout",
              className: styles$b.rowValuePay
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        ContractTurnInActions,
        {
          shortcutLabel: "Items",
          shortcutHref: DEPOSIT_ITEM_URL,
          onTurnIn,
          turnInState,
          turnInError: turnInError2
        }
      )
    ] });
  }
  function CompletedRedeemingFulfillmentPanel({
    fulfillment,
    onClose,
    payoutConversion
  }) {
    const { listing, xanaxTotal, xanaxVerified } = fulfillment;
    const total = xanaxTotal ?? 0;
    const verified = Math.min(xanaxVerified ?? total, total);
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.panel, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: `${styles$b.badge} ${styles$b.badgeCompleted}`, children: "Completed contract" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: styles$b.headline, children: "Contract Complete!" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.details, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Requester" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.partyValue, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "a",
              {
                href: getRequesterProfileUrl(listing.requesterId),
                className: styles$b.sellerLink,
                target: "_blank",
                rel: "noopener noreferrer",
                children: formatRequesterId(listing.requesterId)
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              CopyIdButton,
              {
                id: listing.requesterId,
                label: "Copy requester ID",
                copiedLabel: "Copied"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Xanax sent" }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$b.rowValue, children: [
            verified.toLocaleString("en-US"),
            "/",
            total.toLocaleString("en-US")
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$b.row} tlm-payout-hover-scope`, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Pay" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PayoutValue,
            {
              amount: getRedeemingPayAmount(total),
              conversion: payoutConversion,
              label: "Withdrawal payout",
              className: styles$b.rowValuePay
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ContractCompleteActions, { onClose })
    ] });
  }
  function CompletedServiceFulfillmentPanel({
    label: label2,
    targetLabel,
    targetId,
    targetLink: targetLink2,
    payout: payout2,
    payoutConversion,
    onClose
  }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.panel, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: `${styles$b.badge} ${styles$b.badgeCompleted}`, children: "Completed contract" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: styles$b.headline, children: "Contract Complete!" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.details, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Service" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowValue, children: label2 })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.row, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: targetLabel }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$b.partyValue, children: [
            targetLink2,
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              CopyIdButton,
              {
                id: targetId,
                label: `Copy ${targetLabel.toLowerCase()} ID`,
                copiedLabel: "Copied"
              }
            )
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: `${styles$b.row} tlm-payout-hover-scope`, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$b.rowLabel, children: "Pay" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            PayoutValue,
            {
              amount: payout2,
              conversion: payoutConversion,
              label: `${label2} payout`,
              className: styles$b.rowValuePay
            }
          )
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(ContractCompleteActions, { onClose })
    ] });
  }
  const OTHER_SERVICE_SUBTYPE_OPTIONS = [
    {
      id: "productivity-boost",
      label: "Productivity boost",
      Icon: Building2
    },
    {
      id: "embargo",
      label: "Embargo",
      Icon: Frown
    },
    {
      id: "flight-delay",
      label: "Flight delay",
      Icon: PlaneTakeoff
    },
    {
      id: "references",
      label: "References",
      Icon: UserSearch
    },
    {
      id: "friend-or-foe",
      label: "Friend or Foe",
      Icon: UserCheck
    },
    {
      id: "meditation",
      label: "Meditation",
      Icon: Search
    },
    {
      id: "bounty-reveal",
      label: "Bounty Reveal",
      Icon: Locate
    },
    {
      id: "spies",
      label: "Spies",
      Icon: HatGlasses
    },
    {
      id: "loadout",
      label: "Loadout",
      Icon: Swords
    }
  ];
  function isOtherServiceSubtype(value) {
    return OTHER_SERVICE_SUBTYPE_OPTIONS.some((option) => option.id === value);
  }
  const SUBTYPE_KEY_PREFIX = "other_service_subtype_";
  function subtypeKey(tornXid) {
    return tornXid == null ? `${SUBTYPE_KEY_PREFIX}guest` : `${SUBTYPE_KEY_PREFIX}${tornXid}`;
  }
  function readSync(tornXid) {
    try {
      const raw = readLocalStorageWithMigration(localStorage, subtypeKey(tornXid));
      if (typeof raw === "string" && isOtherServiceSubtype(raw)) return raw;
    } catch {
    }
    return null;
  }
  function writeSync(tornXid, subtype) {
    try {
      writeLocalStorageCurrent(
        localStorage,
        subtypeKey(tornXid),
        subtype ?? ""
      );
    } catch {
    }
  }
  function readStoredOtherServiceSubtypeSync(tornXid) {
    return readSync(tornXid);
  }
  async function loadOtherServiceSubtype(tornXid) {
    const key = subtypeKey(tornXid);
    try {
      const raw = await getPlatformRuntime().storage.get(key);
      if (typeof raw === "string" && isOtherServiceSubtype(raw)) {
        writeSync(tornXid, raw);
        return raw;
      }
      if (raw === "" || raw == null) {
        writeSync(tornXid, null);
        return null;
      }
    } catch {
    }
    return readSync(tornXid);
  }
  async function saveOtherServiceSubtype(tornXid, subtype) {
    writeSync(tornXid, subtype);
    const key = subtypeKey(tornXid);
    try {
      await getPlatformRuntime().storage.set(key, subtype ?? "");
    } catch {
    }
  }
  function ServiceTypeIcon({
    type,
    size = 14,
    className,
    strokeWidth = 2,
    otherSubtype
  }) {
    const props = {
      size,
      className,
      strokeWidth,
      "aria-hidden": true
    };
    switch (type) {
      case "withdrawals":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Pill, { ...props });
      case "bounties":
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Crosshair, { ...props });
      case "other":
        if (otherSubtype === "productivity-boost") return /* @__PURE__ */ jsxRuntimeExports.jsx(Building2, { ...props });
        if (otherSubtype === "embargo") return /* @__PURE__ */ jsxRuntimeExports.jsx(Frown, { ...props });
        if (otherSubtype === "flight-delay") return /* @__PURE__ */ jsxRuntimeExports.jsx(PlaneTakeoff, { ...props });
        if (otherSubtype === "references") return /* @__PURE__ */ jsxRuntimeExports.jsx(UserSearch, { ...props });
        if (otherSubtype === "friend-or-foe") return /* @__PURE__ */ jsxRuntimeExports.jsx(UserCheck, { ...props });
        if (otherSubtype === "meditation") return /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { ...props });
        if (otherSubtype === "bounty-reveal") return /* @__PURE__ */ jsxRuntimeExports.jsx(Locate, { ...props });
        if (otherSubtype === "spies") return /* @__PURE__ */ jsxRuntimeExports.jsx(HatGlasses, { ...props });
        if (otherSubtype === "loadout") return /* @__PURE__ */ jsxRuntimeExports.jsx(Swords, { ...props });
        return /* @__PURE__ */ jsxRuntimeExports.jsx(Handshake, { ...props });
    }
  }
  function ServiceTypePicker({
    value,
    onChange,
    otherSubtype,
    onOtherSubtypeChange,
    disabled = false,
    alertHighlightedTypes,
    alertHighlightedOtherSubtypes,
    "aria-label": ariaLabel = "Service type"
  }) {
    const otherMenuId = reactExports.useId();
    const tablistRef = reactExports.useRef(null);
    const otherWrapRef = reactExports.useRef(null);
    const userInitiatedChangeRef = reactExports.useRef(false);
    const segmentMountedRef = reactExports.useRef(false);
    const [otherMenuOpen, setOtherMenuOpen] = reactExports.useState(false);
    const [segmentPillVisible, setSegmentPillVisible] = reactExports.useState(false);
    const [segmentPillAnimates, setSegmentPillAnimates] = reactExports.useState(false);
    const activeIndex = SERVICE_TYPES.indexOf(value);
    const pillAlert2 = (alertHighlightedTypes == null ? void 0 : alertHighlightedTypes.has(value)) === true;
    const liveOtherOptions = OTHER_SERVICE_SUBTYPE_OPTIONS.filter(
      (option) => isOtherSubtypeEnabled(option.id)
    );
    const otherEnabled = liveOtherOptions.length > 0;
    reactExports.useLayoutEffect(() => {
      if (userInitiatedChangeRef.current) {
        userInitiatedChangeRef.current = false;
        setSegmentPillVisible(true);
        return;
      }
      if (!segmentMountedRef.current) {
        segmentMountedRef.current = true;
        setSegmentPillVisible(true);
        setSegmentPillAnimates(false);
        let animateFrame2 = 0;
        const showFrame2 = requestAnimationFrame(() => {
          animateFrame2 = requestAnimationFrame(() => {
            setSegmentPillAnimates(true);
          });
        });
        return () => {
          cancelAnimationFrame(showFrame2);
          cancelAnimationFrame(animateFrame2);
        };
      }
      setSegmentPillVisible(false);
      setSegmentPillAnimates(false);
      let showFrame = 0;
      let animateFrame = 0;
      const hideFrame = requestAnimationFrame(() => {
        showFrame = requestAnimationFrame(() => {
          setSegmentPillVisible(true);
          animateFrame = requestAnimationFrame(() => {
            setSegmentPillAnimates(true);
          });
        });
      });
      return () => {
        cancelAnimationFrame(hideFrame);
        cancelAnimationFrame(showFrame);
        cancelAnimationFrame(animateFrame);
      };
    }, [value]);
    reactExports.useEffect(() => {
      if (!otherMenuOpen) return;
      const handlePointerDown = (event) => {
        const path = event.composedPath();
        if (!path.includes(otherWrapRef.current)) {
          setOtherMenuOpen(false);
        }
      };
      document.addEventListener("mousedown", handlePointerDown);
      return () => document.removeEventListener("mousedown", handlePointerDown);
    }, [otherMenuOpen]);
    const handleSegmentKeyDown = reactExports.useCallback(
      (e, index) => {
        var _a2, _b;
        let nextIndex = index;
        if (e.key === "ArrowRight" || e.key === "ArrowDown") {
          e.preventDefault();
          nextIndex = (index + 1) % SERVICE_TYPES.length;
        } else if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
          e.preventDefault();
          nextIndex = (index - 1 + SERVICE_TYPES.length) % SERVICE_TYPES.length;
        } else if (e.key === "Home") {
          e.preventDefault();
          nextIndex = 0;
        } else if (e.key === "End") {
          e.preventDefault();
          nextIndex = SERVICE_TYPES.length - 1;
        } else {
          return;
        }
        userInitiatedChangeRef.current = true;
        onChange(SERVICE_TYPES[nextIndex]);
        if (SERVICE_TYPES[nextIndex] !== "other") {
          setOtherMenuOpen(false);
        }
        const tabs2 = (_a2 = tablistRef.current) == null ? void 0 : _a2.querySelectorAll(
          '[role="tab"]'
        );
        (_b = tabs2 == null ? void 0 : tabs2[nextIndex]) == null ? void 0 : _b.focus();
      },
      [onChange]
    );
    const selectOtherSubtype = (subtype) => {
      userInitiatedChangeRef.current = true;
      onChange("other");
      onOtherSubtypeChange(subtype);
      setOtherMenuOpen(false);
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        ref: tablistRef,
        className: styles$g.segment,
        role: "tablist",
        "aria-label": ariaLabel,
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: `${styles$g.segmentPill} ${segmentPillVisible ? "" : styles$g.segmentPillHidden} ${segmentPillAnimates ? "" : styles$g.segmentPillInstant} ${pillAlert2 ? styles$g.segmentPillAlert : ""}`,
              style: { transform: `translateX(${activeIndex * 100}%)` },
              "aria-hidden": "true"
            }
          ),
          SERVICE_TYPES.map((type, index) => {
            const selected = type === value;
            const alertHighlighted = (alertHighlightedTypes == null ? void 0 : alertHighlightedTypes.has(type)) === true;
            if (type === "other") {
              return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "span",
                {
                  ref: otherWrapRef,
                  className: styles$g.segmentOtherWrap,
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      "button",
                      {
                        type: "button",
                        role: "tab",
                        "aria-selected": selected,
                        tabIndex: selected ? 0 : -1,
                        className: `${styles$g.segmentButton} ${alertHighlighted ? styles$g.segmentButtonAlert : ""} ${otherMenuOpen && selected ? styles$g.segmentButtonOtherOpen : ""}`,
                        disabled: disabled || !otherEnabled,
                        "aria-haspopup": "listbox",
                        "aria-expanded": otherMenuOpen && selected,
                        "aria-controls": otherMenuId,
                        onClick: () => {
                          if (!otherEnabled) return;
                          userInitiatedChangeRef.current = true;
                          onChange("other");
                          setOtherMenuOpen((open) => selected ? !open : true);
                        },
                        onKeyDown: (e) => {
                          if (e.key === "Escape") {
                            e.preventDefault();
                            setOtherMenuOpen(false);
                            return;
                          }
                          if (e.key === "ArrowDown" && selected && !otherMenuOpen) {
                            e.preventDefault();
                            setOtherMenuOpen(true);
                            return;
                          }
                          handleSegmentKeyDown(e, index);
                        },
                        children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            ServiceTypeIcon,
                            {
                              type,
                              size: 14,
                              className: styles$g.segmentButtonIcon,
                              otherSubtype
                            }
                          ),
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: SERVICE_TYPE_LABELS[type] }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx(ChevronIcon, { className: styles$g.segmentOtherChevron })
                        ]
                      }
                    ),
                    otherMenuOpen && selected && /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "ul",
                      {
                        id: otherMenuId,
                        className: styles$g.segmentOtherMenu,
                        role: "listbox",
                        "aria-label": "Other services",
                        children: liveOtherOptions.map((option) => {
                          const subtypeSelected = otherSubtype === option.id;
                          const OptionIcon = option.Icon;
                          const optionAlert = (alertHighlightedOtherSubtypes == null ? void 0 : alertHighlightedOtherSubtypes.has(option.id)) === true;
                          return /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "li",
                            {
                              className: styles$g.segmentOtherMenuItem,
                              role: "presentation",
                              children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                                "button",
                                {
                                  type: "button",
                                  role: "option",
                                  "aria-selected": subtypeSelected,
                                  className: `${styles$g.segmentOtherOption} ${optionAlert ? styles$g.segmentOtherOptionAlert : ""} ${option.id === "embargo" || option.id === "flight-delay" ? styles$g.segmentOtherOptionEmbargo : option.id === "references" || option.id === "friend-or-foe" || option.id === "meditation" || option.id === "bounty-reveal" ? styles$g.segmentOtherOptionGray : ""}`,
                                  onClick: () => selectOtherSubtype(option.id),
                                  children: [
                                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                                      OptionIcon,
                                      {
                                        size: 15,
                                        className: styles$g.segmentOtherOptionIcon,
                                        strokeWidth: 1.75,
                                        "aria-hidden": true
                                      }
                                    ),
                                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: option.label })
                                  ]
                                }
                              )
                            },
                            option.id
                          );
                        })
                      }
                    )
                  ]
                },
                type
              );
            }
            return /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "button",
              {
                type: "button",
                role: "tab",
                "aria-selected": selected,
                tabIndex: selected ? 0 : -1,
                className: `${styles$g.segmentButton} ${alertHighlighted ? styles$g.segmentButtonAlert : ""}`,
                disabled,
                onClick: () => {
                  userInitiatedChangeRef.current = true;
                  onChange(type);
                  setOtherMenuOpen(false);
                },
                onKeyDown: (e) => handleSegmentKeyDown(e, index),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    ServiceTypeIcon,
                    {
                      type,
                      size: 14,
                      className: styles$g.segmentButtonIcon
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: SERVICE_TYPE_LABELS[type] })
                ]
              },
              type
            );
          })
        ]
      }
    );
  }
  function ChevronIcon({ className }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "svg",
      {
        className,
        width: "10",
        height: "10",
        viewBox: "0 0 24 24",
        fill: "none",
        "aria-hidden": true,
        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          "path",
          {
            d: "M6 9l6 6 6-6",
            stroke: "currentColor",
            strokeWidth: "2",
            strokeLinecap: "round",
            strokeLinejoin: "round"
          }
        )
      }
    );
  }
  const PRODUCTIVITY_BOOST_COLUMNS = [
    { id: "target", label: "Target" },
    { id: "pay", label: "Pay" }
  ];
  const EMBARGO_COLUMNS = [
    { id: "target", label: "Target" },
    { id: "pay", label: "Pay" }
  ];
  const FLIGHT_DELAY_COLUMNS = [
    { id: "target", label: "Target" },
    { id: "pay", label: "Pay" }
  ];
  const SIMPLE_SERVICE_COLUMNS = [
    { id: "target", label: "Target" },
    { id: "pay", label: "Pay" }
  ];
  const BOUNTY_COLUMNS = [
    { id: "cost", label: "Bounty cost" },
    { id: "quantity", label: "Quantity" },
    { id: "pay", label: "Pay" }
  ];
  const WITHDRAWAL_COLUMNS = [
    { field: "requesterId", label: "Requesters" },
    { field: "quantity", label: "Quantity" },
    { field: "pay", label: "Pay" }
  ];
  function SortIndicator({
    active,
    descending
  }) {
    if (!active) return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$9.sortIdle, "aria-hidden": "true" });
    return /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$9.sortActive, "aria-hidden": "true", children: descending ? "↓" : "↑" });
  }
  function RedeemingPanel({
    balance,
    listings,
    ownListingIds,
    onListingSelect,
    onCancelRequest,
    showRedeemContractPanel,
    showRedeemCompletedPanel,
    displayRedeemFulfillment,
    completedRedeemFulfillment,
    redeemingSecondsRemaining,
    onDismissCompletedRedeem,
    completedService,
    onDismissCompletedService,
    highlightedListingId,
    onTurnInFulfillment,
    redeemTurnInState,
    redeemTurnInError,
    payoutConversion,
    onOpenSettings,
    navRequest,
    tornXid,
    sessionLoading = false,
    withdrawalAlertActive = false,
    bountyAlertActive = false,
    embargoAlertActive = false,
    productivityAlertActive = false,
    flightDelayAlertActive = false,
    simpleServiceAlertActive = false,
    alertingOtherSubtypes,
    alertWithdrawalThreshold = null,
    alertBountyThreshold = null,
    alertEmbargoThreshold = null,
    alertProductivityThreshold = null,
    alertFlightDelayThreshold = null,
    alertSimpleServiceThresholds = {},
    onAlertWithdrawalThresholdChange = () => {
    },
    onAlertBountyThresholdChange = () => {
    },
    onAlertEmbargoThresholdChange = () => {
    },
    onAlertProductivityThresholdChange = () => {
    },
    onAlertFlightDelayThresholdChange = () => {
    },
    onAlertSimpleServiceThresholdChange = () => {
    },
    bountyOrders = [],
    ownBountyOrderIds = /* @__PURE__ */ new Set(),
    onBountyOrderSelect,
    onCancelBountyOrder,
    showBountyContractPanel,
    displayBountyFulfillment,
    bountySecondsRemaining,
    onTurnInBountyFulfillment,
    bountyTurnInState,
    bountyTurnInError,
    productivityBoostListings = [],
    onCancelProductivityBoost,
    onTakeProductivityBoost,
    showProductivityBoostContractPanel,
    activeProductivityBoostFulfillment,
    productivityBoostSecondsRemaining,
    onTurnInProductivityBoost,
    productivityBoostTurnInState,
    productivityBoostTurnInError,
    embargoListings = [],
    onCancelEmbargo,
    onTakeEmbargo,
    showEmbargoContractPanel,
    activeEmbargoFulfillment,
    embargoSecondsRemaining,
    onTurnInEmbargo,
    embargoTurnInState,
    embargoTurnInError,
    referencesListings = [],
    onCancelReferences,
    onTakeReferences,
    showReferencesContractPanel,
    activeReferencesFulfillment,
    referencesSecondsRemaining,
    onTurnInReferences,
    referencesTurnInState,
    referencesTurnInError,
    bountyRevealListings = [],
    onCancelBountyReveal,
    onTakeBountyReveal,
    showBountyRevealContractPanel,
    activeBountyRevealFulfillment,
    bountyRevealSecondsRemaining,
    onTurnInBountyReveal,
    bountyRevealTurnInState,
    bountyRevealTurnInError,
    flightDelayListings = [],
    onCancelFlightDelay,
    onTakeFlightDelay,
    showFlightDelayContractPanel,
    activeFlightDelayFulfillment,
    flightDelaySecondsRemaining,
    onTurnInFlightDelay,
    flightDelayTurnInState,
    flightDelayTurnInError,
    simpleServiceListings = [],
    onCancelSimpleService,
    onTakeSimpleService,
    showSimpleServiceContractPanel,
    activeSimpleServiceFulfillment,
    simpleServiceSecondsRemaining,
    onTurnInSimpleService,
    simpleServiceTurnInState,
    simpleServiceTurnInError
  }) {
    var _a2;
    const [serviceType, setServiceType] = reactExports.useState(() => {
      if (sessionLoading) return null;
      return readStoredServiceTypeSync(tornXid) ?? "withdrawals";
    });
    const [otherSubtype, setOtherSubtype] = reactExports.useState(
      () => {
        if (sessionLoading) return null;
        return readStoredOtherServiceSubtypeSync(tornXid);
      }
    );
    const [sortField, setSortField] = reactExports.useState("quantity");
    const [sortDescending, setSortDescending] = reactExports.useState(true);
    const [alertOpen, setAlertOpen] = reactExports.useState(false);
    const navOverrideRef = reactExports.useRef(false);
    reactExports.useEffect(() => {
      if (sessionLoading) return;
      navOverrideRef.current = false;
      const cached = readStoredServiceTypeSync(tornXid) ?? "withdrawals";
      setServiceType(cached);
      let cancelled = false;
      void loadServiceType(tornXid).then((stored) => {
        if (!cancelled && !navOverrideRef.current) setServiceType(stored);
      });
      setOtherSubtype(readStoredOtherServiceSubtypeSync(tornXid));
      void loadOtherServiceSubtype(tornXid).then((stored) => {
        if (!cancelled && !navOverrideRef.current) setOtherSubtype(stored);
      });
      return () => {
        cancelled = true;
      };
    }, [tornXid, sessionLoading]);
    const handleServiceTypeChange = (next) => {
      setServiceType(next);
      void saveServiceType(tornXid, next);
    };
    const handleOtherSubtypeChange = (next) => {
      setOtherSubtype(next);
      void saveOtherServiceSubtype(tornXid, next);
    };
    const navToken = navRequest == null ? void 0 : navRequest.token;
    reactExports.useEffect(() => {
      if (!navRequest) return;
      navOverrideRef.current = true;
      handleServiceTypeChange(navRequest.serviceType);
      if (navRequest.otherSubtype) {
        handleOtherSubtypeChange(navRequest.otherSubtype);
      }
    }, [navToken]);
    const activeServiceType = serviceType ?? "withdrawals";
    const averageXanaxPrice = ((_a2 = payoutConversion.price) == null ? void 0 : _a2.averagePrice) ?? null;
    const openBountyOrders = reactExports.useMemo(
      () => [...bountyOrders.filter(isVisibleBountyMarketOrder)].sort(
        (a, b) => a.bountyValueTorn - b.bountyValueTorn
      ),
      [bountyOrders]
    );
    const sortedProductivityBoostListings = reactExports.useMemo(
      () => [...productivityBoostListings].sort(
        (a, b) => b.escrowedPts - a.escrowedPts
      ),
      [productivityBoostListings]
    );
    const sortedEmbargoListings = reactExports.useMemo(
      () => [...embargoListings].sort((a, b) => b.escrowedPts - a.escrowedPts),
      [embargoListings]
    );
    const sortedReferencesListings = reactExports.useMemo(
      () => [...referencesListings].sort((a, b) => b.escrowedPts - a.escrowedPts),
      [referencesListings]
    );
    const referencesSellBlocked = isWebPlatform();
    const sortedBountyRevealListings = reactExports.useMemo(
      () => [...bountyRevealListings].sort((a, b) => b.escrowedPts - a.escrowedPts),
      [bountyRevealListings]
    );
    const bountyRevealSellBlocked = isWebPlatform();
    const sortedFlightDelayListings = reactExports.useMemo(
      () => [...flightDelayListings].sort((a, b) => b.escrowedPts - a.escrowedPts),
      [flightDelayListings]
    );
    const liveOtherSubtype = otherSubtype != null && isOtherSubtypeEnabled(otherSubtype) ? otherSubtype : null;
    const activeSimpleServiceKind = liveOtherSubtype != null && isSimpleServiceId(liveOtherSubtype) ? liveOtherSubtype : null;
    const sortedSimpleServiceListings = reactExports.useMemo(
      () => [...simpleServiceListings].filter((s) => s.kind === activeSimpleServiceKind).sort((a, b) => b.escrowedPts - a.escrowedPts),
      [simpleServiceListings, activeSimpleServiceKind]
    );
    const sortedListings = reactExports.useMemo(
      () => sortRedeemingListings(listings, sortField, sortDescending),
      [listings, sortField, sortDescending]
    );
    const handleHeaderClick = (field2) => {
      if (field2 === sortField) {
        setSortDescending((d) => !d);
      } else {
        setSortField(field2);
        setSortDescending(true);
      }
    };
    const serviceTypeAlertHighlights = reactExports.useMemo(() => {
      const highlighted = /* @__PURE__ */ new Set();
      if (withdrawalAlertActive) highlighted.add("withdrawals");
      if (bountyAlertActive) highlighted.add("bounties");
      if (embargoAlertActive || productivityAlertActive || flightDelayAlertActive || simpleServiceAlertActive) {
        highlighted.add("other");
      }
      return highlighted.size > 0 ? highlighted : void 0;
    }, [
      withdrawalAlertActive,
      bountyAlertActive,
      embargoAlertActive,
      productivityAlertActive,
      flightDelayAlertActive,
      simpleServiceAlertActive
    ]);
    const activeAlert = (() => {
      if (activeServiceType === "withdrawals") {
        return {
          label: "Withdrawals",
          kind: "quantity",
          value: alertWithdrawalThreshold,
          onCommit: onAlertWithdrawalThresholdChange
        };
      }
      if (activeServiceType === "bounties") {
        return {
          label: "Bounties",
          kind: "quantity",
          value: alertBountyThreshold,
          onCommit: onAlertBountyThresholdChange
        };
      }
      if (liveOtherSubtype === "productivity-boost") {
        return {
          label: "Productivity",
          kind: "price",
          value: alertProductivityThreshold,
          onCommit: onAlertProductivityThresholdChange,
          singular: "boost"
        };
      }
      if (liveOtherSubtype === "embargo") {
        return {
          label: "Embargo",
          kind: "price",
          value: alertEmbargoThreshold,
          onCommit: onAlertEmbargoThresholdChange,
          singular: "embargo"
        };
      }
      if (liveOtherSubtype === "flight-delay") {
        return {
          label: "Flight delay",
          kind: "price",
          value: alertFlightDelayThreshold,
          onCommit: onAlertFlightDelayThresholdChange,
          singular: "flight delay"
        };
      }
      if (activeSimpleServiceKind !== null) {
        const kind = activeSimpleServiceKind;
        return {
          label: SIMPLE_SERVICES[kind].label,
          kind: "price",
          value: alertSimpleServiceThresholds[kind] ?? null,
          onCommit: (v) => onAlertSimpleServiceThresholdChange(kind, v),
          singular: SIMPLE_SERVICES[kind].label.toLowerCase()
        };
      }
      return null;
    })();
    const openAlert = tornXid === null || !activeAlert ? onOpenSettings : () => setAlertOpen(true);
    if (showRedeemContractPanel && displayRedeemFulfillment) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        ActiveRedeemingFulfillmentPanel,
        {
          fulfillment: displayRedeemFulfillment,
          secondsRemaining: redeemingSecondsRemaining,
          onTurnIn: onTurnInFulfillment,
          turnInState: redeemTurnInState,
          turnInError: redeemTurnInError,
          payoutConversion
        }
      );
    }
    if (showBountyContractPanel && displayBountyFulfillment) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        ActiveBountyFulfillmentPanel,
        {
          fulfillment: displayBountyFulfillment,
          secondsRemaining: bountySecondsRemaining,
          onTurnIn: onTurnInBountyFulfillment,
          turnInState: bountyTurnInState,
          turnInError: bountyTurnInError,
          payoutConversion
        }
      );
    }
    if (showProductivityBoostContractPanel && activeProductivityBoostFulfillment) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        ActiveProductivityBoostFulfillmentPanel,
        {
          boost: activeProductivityBoostFulfillment,
          secondsRemaining: productivityBoostSecondsRemaining,
          onTurnIn: onTurnInProductivityBoost,
          turnInState: productivityBoostTurnInState,
          turnInError: productivityBoostTurnInError,
          payoutConversion
        }
      );
    }
    if (showEmbargoContractPanel && activeEmbargoFulfillment) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        ActiveEmbargoFulfillmentPanel,
        {
          embargo: activeEmbargoFulfillment,
          secondsRemaining: embargoSecondsRemaining,
          onTurnIn: onTurnInEmbargo,
          turnInState: embargoTurnInState,
          turnInError: embargoTurnInError,
          payoutConversion
        }
      );
    }
    if (showReferencesContractPanel && activeReferencesFulfillment) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        ActiveSimpleServiceFulfillmentPanel,
        {
          config: SIMPLE_SERVICES.references,
          service: {
            id: activeReferencesFulfillment.id,
            kind: "references",
            targetUserId: activeReferencesFulfillment.targetUserId,
            priceTorn: activeReferencesFulfillment.priceTorn,
            escrowedPts: activeReferencesFulfillment.escrowedPts,
            status: "open",
            createdAt: activeReferencesFulfillment.createdAt
          },
          secondsRemaining: referencesSecondsRemaining,
          onTurnIn: onTurnInReferences,
          turnInState: referencesTurnInState,
          turnInError: referencesTurnInError,
          payoutConversion
        }
      );
    }
    if (showBountyRevealContractPanel && activeBountyRevealFulfillment) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        ActiveSimpleServiceFulfillmentPanel,
        {
          config: SIMPLE_SERVICES["bounty-reveal"],
          service: {
            id: activeBountyRevealFulfillment.id,
            kind: "bounty-reveal",
            targetUserId: activeBountyRevealFulfillment.targetUserId,
            priceTorn: activeBountyRevealFulfillment.priceTorn,
            escrowedPts: activeBountyRevealFulfillment.escrowedPts,
            status: "open",
            createdAt: activeBountyRevealFulfillment.createdAt
          },
          secondsRemaining: bountyRevealSecondsRemaining,
          onTurnIn: onTurnInBountyReveal,
          turnInState: bountyRevealTurnInState,
          turnInError: bountyRevealTurnInError,
          payoutConversion
        }
      );
    }
    if (showFlightDelayContractPanel && activeFlightDelayFulfillment) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        ActiveFlightDelayFulfillmentPanel,
        {
          flightDelay: activeFlightDelayFulfillment,
          secondsRemaining: flightDelaySecondsRemaining,
          onTurnIn: onTurnInFlightDelay,
          turnInState: flightDelayTurnInState,
          turnInError: flightDelayTurnInError,
          payoutConversion
        }
      );
    }
    if (showSimpleServiceContractPanel && activeSimpleServiceFulfillment) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        ActiveSimpleServiceFulfillmentPanel,
        {
          config: SIMPLE_SERVICES[activeSimpleServiceFulfillment.kind],
          service: activeSimpleServiceFulfillment,
          secondsRemaining: simpleServiceSecondsRemaining,
          onTurnIn: onTurnInSimpleService,
          turnInState: simpleServiceTurnInState,
          turnInError: simpleServiceTurnInError,
          payoutConversion
        }
      );
    }
    if (showRedeemCompletedPanel && completedRedeemFulfillment) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        CompletedRedeemingFulfillmentPanel,
        {
          fulfillment: completedRedeemFulfillment,
          onClose: onDismissCompletedRedeem,
          payoutConversion
        }
      );
    }
    if (completedService) {
      const isCompany = completedService.targetKind === "company";
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        CompletedServiceFulfillmentPanel,
        {
          label: completedService.label,
          targetLabel: isCompany ? "Company" : "Target",
          targetId: completedService.targetId,
          targetLink: isCompany ? /* @__PURE__ */ jsxRuntimeExports.jsx(ProductivityBoostCompanyLink, { companyId: completedService.targetId }) : /* @__PURE__ */ jsxRuntimeExports.jsx(SimpleServiceTargetLink, { targetUserId: completedService.targetId }),
          payout: completedService.payout,
          payoutConversion,
          onClose: onDismissCompletedService
        }
      );
    }
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.panel, role: "region", "aria-label": "Sell Services", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.typePickerBar, children: !sessionLoading && serviceType !== null && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.pickerRowMain, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          ServiceTypePicker,
          {
            value: serviceType,
            onChange: handleServiceTypeChange,
            otherSubtype,
            onOtherSubtypeChange: handleOtherSubtypeChange,
            "aria-label": "Service type",
            alertHighlightedTypes: serviceTypeAlertHighlights,
            alertHighlightedOtherSubtypes: alertingOtherSubtypes
          }
        ) }),
        activeAlert && /* @__PURE__ */ jsxRuntimeExports.jsx(
          AlertBellPopover,
          {
            label: activeAlert.label,
            kind: activeAlert.kind,
            singular: activeAlert.singular,
            value: activeAlert.value,
            onCommit: activeAlert.onCommit,
            balance,
            disabled: tornXid === null,
            open: alertOpen,
            onOpenChange: setAlertOpen,
            size: 44
          }
        )
      ] }) }),
      activeServiceType === "withdrawals" ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.table, role: "table", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHead, role: "rowgroup", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHeaderRow, role: "row", children: WITHDRAWAL_COLUMNS.map(({ field: field2, label: label2 }) => {
          const active = sortField === field2;
          return /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "button",
            {
              type: "button",
              role: "columnheader",
              "aria-sort": active ? sortDescending ? "descending" : "ascending" : "none",
              className: `${styles$9.columnHeader} ${active ? styles$9.columnHeaderActive : ""}`,
              onClick: () => handleHeaderClick(field2),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: label2 }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(SortIndicator, { active, descending: sortDescending })
              ]
            },
            field2
          );
        }) }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableBody, role: "rowgroup", children: sortedListings.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
          MarketListingsEmptyState,
          {
            message: "No withdrawal listings yet.",
            onSetAlert: openAlert,
            alertThreshold: alertWithdrawalThreshold,
            formatAlertThreshold: (value) => value.toLocaleString("en-US")
          }
        ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
          AnimatedList,
          {
            className: styles$9.list,
            itemClassName: "tlm-table-row-item",
            selectOnHover: false,
            items: sortedListings,
            getItemKey: (item) => item.id,
            showGradients: true,
            enableArrowNavigation: true,
            displayScrollbar: true,
            dense: true,
            listAriaLabel: "Withdrawal requests",
            onItemSelect: (listing) => {
              const isOwn = ownListingIds.has(listing.id);
              const isReserved = listing.quantity === 0;
              if (isOwn || isReserved) return;
              onListingSelect(listing);
            },
            renderItem: (listing) => {
              const isOwn = ownListingIds.has(listing.id);
              const isReserved = listing.quantity === 0;
              const isSelectable = !isOwn && !isReserved;
              const isHighlighted = listing.id === highlightedListingId;
              const takeContract = () => onListingSelect(listing);
              const rowLabel2 = isOwn ? `Your withdrawal request, ${listing.quantity} xanax, ${formatRedeemingPay(listing.quantity)} pay` : isReserved ? `Requester ${formatRequesterId(listing.requesterId)}, fully reserved at ${formatRedeemingPay(listing.quantity)} pay` : `Requester ${formatRequesterId(listing.requesterId)}, ${listing.quantity} xanax, ${formatRedeemingPay(listing.quantity)} pay — ${takeContractRowHint()}`;
              return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "div",
                {
                  className: [
                    styles$9.tableRow,
                    "tlm-payout-hover-scope",
                    isSelectable ? styles$9.tableRowSelectable : "",
                    isHighlighted ? styles$9.tableRowHighlighted : "",
                    isOwn && !isHighlighted ? styles$9.tableRowOwn : "",
                    isReserved && !isOwn ? styles$9.tableRowReserved : ""
                  ].filter(Boolean).join(" "),
                  role: "row",
                  "aria-label": rowLabel2,
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.rowCells, children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellSeller}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "a",
                        {
                          href: getRequesterProfileUrl(listing.requesterId),
                          className: styles$9.sellerLink,
                          onClick: (e) => e.stopPropagation(),
                          children: formatRequesterId(listing.requesterId)
                        }
                      ) }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellQuantity}`, children: isReserved ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$9.fullyReservedBadge, children: "Fully reserved" }) : listing.quantity.toLocaleString("en-US") }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellPay}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                        PayoutValue,
                        {
                          amount: getRedeemingPayAmount(listing.quantity),
                          conversion: payoutConversion,
                          label: "Withdrawal payout"
                        }
                      ) })
                    ] }),
                    isSelectable && /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        className: styles$9.takeContractBtn,
                        onClick: (e) => {
                          e.stopPropagation();
                          takeContract();
                        },
                        children: TAKE_CONTRACT_BUTTON_LABEL
                      }
                    ),
                    isOwn && !isReserved && /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        className: styles$9.cancelRedeem,
                        "aria-label": "Cancel withdrawal request",
                        onClick: (e) => {
                          e.stopPropagation();
                          onCancelRequest(listing);
                        },
                        children: "×"
                      }
                    )
                  ]
                }
              );
            }
          }
        ) })
      ] }) : activeServiceType === "bounties" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: `${styles$9.table} ${styles$9.tableBounties}`,
          role: "table",
          "aria-label": "Bounty listings",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHead, role: "rowgroup", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHeaderRow, role: "row", children: BOUNTY_COLUMNS.map(({ id: id2, label: label2 }) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              "span",
              {
                role: "columnheader",
                className: [
                  styles$9.columnHeader,
                  id2 === "quantity" ? styles$9.bountyColumnHeaderQuantity : ""
                ].filter(Boolean).join(" "),
                children: label2
              },
              id2
            )) }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableBody, role: "rowgroup", children: openBountyOrders.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              MarketListingsEmptyState,
              {
                message: "No bounty listings yet.",
                onSetAlert: openAlert,
                alertThreshold: alertBountyThreshold,
                formatAlertThreshold: (value) => value.toLocaleString("en-US")
              }
            ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
              AnimatedList,
              {
                className: styles$9.list,
                itemClassName: "tlm-table-row-item",
                selectOnHover: false,
                items: openBountyOrders,
                getItemKey: (item) => item.id,
                showGradients: true,
                enableArrowNavigation: true,
                displayScrollbar: true,
                dense: true,
                listAriaLabel: "Bounty listings",
                onItemSelect: (order) => {
                  const isOwn = ownBountyOrderIds.has(order.id) || tornXid != null && order.buyerId === tornXid;
                  const isReserved = order.quantityRemaining === 0;
                  if (isOwn || isReserved) return;
                  onBountyOrderSelect(order);
                },
                renderItem: (order) => {
                  const isOwn = ownBountyOrderIds.has(order.id) || tornXid != null && order.buyerId === tornXid;
                  const isReserved = order.quantityRemaining === 0;
                  const isSelectable = !isOwn && !isReserved;
                  const bountyCostTorn = computeBountyPlacementCostTorn(
                    order.bountyValueTorn
                  );
                  const payPts = computeBountyPerContractPts(
                    order.bountyValueTorn,
                    averageXanaxPrice,
                    convertTornDollarsToScriptPoints
                  ).totalPts;
                  const takeContract = () => onBountyOrderSelect(order);
                  const rowLabel2 = isOwn ? `Your bounty order, ${order.quantityRemaining} remaining at ${formatMoney(order.bountyValueTorn)} each` : isReserved ? `Bounty fully reserved at ${formatMoney(order.bountyValueTorn)} each` : `${order.quantityRemaining} bounties at ${formatMoney(order.bountyValueTorn)} each — ${takeContractRowHint()}`;
                  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "div",
                    {
                      className: [
                        styles$9.tableRow,
                        "tlm-payout-hover-scope",
                        isSelectable ? styles$9.tableRowSelectable : "",
                        isOwn ? styles$9.tableRowOwn : "",
                        isReserved && !isOwn ? styles$9.tableRowReserved : ""
                      ].filter(Boolean).join(" "),
                      role: "row",
                      "aria-label": rowLabel2,
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.rowCells, children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellSeller}`, children: formatMoney(bountyCostTorn) }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "span",
                            {
                              className: `${styles$9.cell} ${styles$9.bountyCellQuantity}`,
                              children: isReserved ? /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$9.fullyReservedBadge, children: "Fully reserved" }) : order.quantityRemaining.toLocaleString("en-US")
                            }
                          ),
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellPay}`, children: payPts != null ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                            PayoutValue,
                            {
                              amount: payPts,
                              conversion: payoutConversion,
                              label: "Bounty fulfillment pay"
                            }
                          ) : "—" })
                        ] }),
                        isSelectable && /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "button",
                          {
                            type: "button",
                            className: styles$9.takeContractBtn,
                            onClick: (e) => {
                              e.stopPropagation();
                              takeContract();
                            },
                            children: TAKE_CONTRACT_BUTTON_LABEL
                          }
                        ),
                        isOwn && !isReserved && /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "button",
                          {
                            type: "button",
                            className: styles$9.cancelRedeem,
                            "aria-label": "Cancel bounty order and refund remaining balance",
                            onClick: (e) => {
                              e.stopPropagation();
                              onCancelBountyOrder(order);
                            },
                            children: "×"
                          }
                        )
                      ]
                    }
                  );
                }
              }
            ) })
          ]
        }
      ) : liveOtherSubtype === "productivity-boost" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: `${styles$9.table} ${styles$9.tableProductivityBoost}`,
          role: "table",
          "aria-label": "Productivity boost listings",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHead, role: "rowgroup", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHeaderRow, role: "row", children: PRODUCTIVITY_BOOST_COLUMNS.map(({ id: id2, label: label2 }) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              "span",
              {
                role: "columnheader",
                className: [
                  styles$9.columnHeader,
                  id2 === "pay" ? styles$9.cellPay : ""
                ].filter(Boolean).join(" "),
                children: label2
              },
              id2
            )) }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableBody, role: "rowgroup", children: productivityBoostListings.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              MarketListingsEmptyState,
              {
                message: "No productivity boost listings yet.",
                onSetAlert: openAlert,
                alertThreshold: null,
                formatAlertThreshold: (value) => value.toLocaleString("en-US")
              }
            ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
              AnimatedList,
              {
                className: styles$9.list,
                itemClassName: "tlm-table-row-item",
                selectOnHover: false,
                items: sortedProductivityBoostListings,
                getItemKey: (item) => item.id,
                showGradients: true,
                enableArrowNavigation: true,
                displayScrollbar: true,
                dense: true,
                listAriaLabel: "Productivity boost listings",
                onItemSelect: () => {
                },
                renderItem: (boost) => {
                  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "div",
                    {
                      className: [
                        styles$9.tableRow,
                        styles$9.tableRowSelectable,
                        styles$9.tableRowOwn,
                        "tlm-payout-hover-scope"
                      ].filter(Boolean).join(" "),
                      role: "row",
                      "aria-label": `Company ${boost.companyId}, ${boost.escrowedPts.toLocaleString("en-US")} PTS pay${" (your order)"}`,
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.rowCells, children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellSeller}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                            ProductivityBoostCompanyLink,
                            {
                              companyId: boost.companyId
                            }
                          ) }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellPay}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                            PayoutValue,
                            {
                              amount: boost.escrowedPts,
                              conversion: payoutConversion,
                              label: "Productivity boost pay"
                            }
                          ) })
                        ] }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "button",
                          {
                            type: "button",
                            className: styles$9.takeContractBtn,
                            onClick: (e) => {
                              e.stopPropagation();
                              onTakeProductivityBoost(boost);
                            },
                            children: TAKE_CONTRACT_BUTTON_LABEL
                          }
                        ),
                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "button",
                          {
                            type: "button",
                            className: styles$9.cancelRedeem,
                            "aria-label": "Cancel productivity boost order",
                            onClick: (e) => {
                              e.stopPropagation();
                              onCancelProductivityBoost(boost);
                            },
                            children: "×"
                          }
                        )
                      ]
                    }
                  );
                }
              }
            ) })
          ]
        }
      ) : liveOtherSubtype === "embargo" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: `${styles$9.table} ${styles$9.tableProductivityBoost}`,
          role: "table",
          "aria-label": "Embargo listings",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHead, role: "rowgroup", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHeaderRow, role: "row", children: EMBARGO_COLUMNS.map(({ id: id2, label: label2 }) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              "span",
              {
                role: "columnheader",
                className: [
                  styles$9.columnHeader,
                  id2 === "pay" ? styles$9.cellPay : ""
                ].filter(Boolean).join(" "),
                children: label2
              },
              id2
            )) }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableBody, role: "rowgroup", children: embargoListings.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              MarketListingsEmptyState,
              {
                message: "No embargo listings yet.",
                onSetAlert: openAlert,
                alertThreshold: null,
                formatAlertThreshold: (value) => value.toLocaleString("en-US")
              }
            ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
              AnimatedList,
              {
                className: styles$9.list,
                itemClassName: "tlm-table-row-item",
                selectOnHover: false,
                items: sortedEmbargoListings,
                getItemKey: (item) => item.id,
                showGradients: true,
                enableArrowNavigation: true,
                displayScrollbar: true,
                dense: true,
                listAriaLabel: "Embargo listings",
                onItemSelect: () => {
                },
                renderItem: (embargo) => {
                  const isOwn = embargo.buyerXid != null && embargo.buyerXid === tornXid;
                  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "div",
                    {
                      className: [
                        styles$9.tableRow,
                        !isOwn ? styles$9.tableRowSelectable : "",
                        isOwn ? styles$9.tableRowOwn : "",
                        "tlm-payout-hover-scope"
                      ].filter(Boolean).join(" "),
                      role: "row",
                      "aria-label": `Target ${embargo.targetUserId}, ${embargo.escrowedPts.toLocaleString("en-US")} PTS pay${isOwn ? " (your order)" : ""}`,
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.rowCells, children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellSeller}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                            EmbargoTargetLink,
                            {
                              targetUserId: embargo.targetUserId
                            }
                          ) }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellPay}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                            PayoutValue,
                            {
                              amount: embargo.escrowedPts,
                              conversion: payoutConversion,
                              label: "Embargo pay"
                            }
                          ) })
                        ] }),
                        !isOwn && /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "button",
                          {
                            type: "button",
                            className: styles$9.takeContractBtn,
                            onClick: (e) => {
                              e.stopPropagation();
                              onTakeEmbargo(embargo);
                            },
                            children: TAKE_CONTRACT_BUTTON_LABEL
                          }
                        ),
                        isOwn && /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "button",
                          {
                            type: "button",
                            className: styles$9.cancelRedeem,
                            "aria-label": "Cancel embargo order",
                            onClick: (e) => {
                              e.stopPropagation();
                              onCancelEmbargo(embargo);
                            },
                            children: "×"
                          }
                        )
                      ]
                    }
                  );
                }
              }
            ) })
          ]
        }
      ) : liveOtherSubtype === "flight-delay" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: `${styles$9.table} ${styles$9.tableProductivityBoost}`,
          role: "table",
          "aria-label": "Flight delay listings",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHead, role: "rowgroup", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHeaderRow, role: "row", children: FLIGHT_DELAY_COLUMNS.map(({ id: id2, label: label2 }) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              "span",
              {
                role: "columnheader",
                className: [
                  styles$9.columnHeader,
                  id2 === "pay" ? styles$9.cellPay : ""
                ].filter(Boolean).join(" "),
                children: label2
              },
              id2
            )) }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableBody, role: "rowgroup", children: flightDelayListings.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              MarketListingsEmptyState,
              {
                message: "No flight delay listings yet.",
                onSetAlert: openAlert,
                alertThreshold: null,
                formatAlertThreshold: (value) => value.toLocaleString("en-US")
              }
            ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
              AnimatedList,
              {
                className: styles$9.list,
                itemClassName: "tlm-table-row-item",
                selectOnHover: false,
                items: sortedFlightDelayListings,
                getItemKey: (item) => item.id,
                showGradients: true,
                enableArrowNavigation: true,
                displayScrollbar: true,
                dense: true,
                listAriaLabel: "Flight delay listings",
                onItemSelect: () => {
                },
                renderItem: (flightDelay) => {
                  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "div",
                    {
                      className: [
                        styles$9.tableRow,
                        styles$9.tableRowSelectable,
                        styles$9.tableRowOwn,
                        "tlm-payout-hover-scope"
                      ].filter(Boolean).join(" "),
                      role: "row",
                      "aria-label": `Target ${flightDelay.targetUserId}, ${flightDelay.escrowedPts.toLocaleString("en-US")} PTS pay${" (your order)"}`,
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.rowCells, children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellSeller}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                            FlightDelayTargetLink,
                            {
                              targetUserId: flightDelay.targetUserId
                            }
                          ) }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellPay}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                            PayoutValue,
                            {
                              amount: flightDelay.escrowedPts,
                              conversion: payoutConversion,
                              label: "Flight delay pay"
                            }
                          ) })
                        ] }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "button",
                          {
                            type: "button",
                            className: styles$9.takeContractBtn,
                            onClick: (e) => {
                              e.stopPropagation();
                              onTakeFlightDelay(flightDelay);
                            },
                            children: TAKE_CONTRACT_BUTTON_LABEL
                          }
                        ),
                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "button",
                          {
                            type: "button",
                            className: styles$9.cancelRedeem,
                            "aria-label": "Cancel flight delay order",
                            onClick: (e) => {
                              e.stopPropagation();
                              onCancelFlightDelay(flightDelay);
                            },
                            children: "×"
                          }
                        )
                      ]
                    }
                  );
                }
              }
            ) })
          ]
        }
      ) : liveOtherSubtype === "references" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: `${styles$9.table} ${styles$9.tableProductivityBoost}`,
          role: "table",
          "aria-label": "References listings",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHead, role: "rowgroup", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHeaderRow, role: "row", children: SIMPLE_SERVICE_COLUMNS.map(({ id: id2, label: label2 }) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              "span",
              {
                role: "columnheader",
                className: [
                  styles$9.columnHeader,
                  id2 === "pay" ? styles$9.cellPay : ""
                ].filter(Boolean).join(" "),
                children: label2
              },
              id2
            )) }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.tableBody, role: "rowgroup", children: [
              referencesSellBlocked && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.webSellNotice, role: "note", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("strong", { className: styles$9.webSellNoticeTitle, children: "Selling references needs the app" }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
                  "References are pulled from the in-game company special, which the website can't read. Install the",
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "a",
                    {
                      href: CHROME_WEB_STORE_URL,
                      target: "_blank",
                      rel: "noopener noreferrer",
                      children: "Chrome extension"
                    }
                  ),
                  " ",
                  "or the",
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "a",
                    {
                      href: GREASY_FORK_URL,
                      target: "_blank",
                      rel: "noopener noreferrer",
                      children: "userscript"
                    }
                  ),
                  " ",
                  "to fulfill them."
                ] })
              ] }),
              sortedReferencesListings.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                MarketListingsEmptyState,
                {
                  message: "No references listings yet.",
                  onSetAlert: openAlert,
                  alertThreshold: null,
                  formatAlertThreshold: (value) => value.toLocaleString("en-US")
                }
              ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
                AnimatedList,
                {
                  className: styles$9.list,
                  itemClassName: "tlm-table-row-item",
                  selectOnHover: false,
                  items: sortedReferencesListings,
                  getItemKey: (item) => item.id,
                  showGradients: true,
                  enableArrowNavigation: true,
                  displayScrollbar: true,
                  dense: true,
                  listAriaLabel: "References listings",
                  onItemSelect: () => {
                  },
                  renderItem: (order) => {
                    const isOwn = order.buyerXid != null && order.buyerXid === tornXid;
                    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      "div",
                      {
                        className: [
                          styles$9.tableRow,
                          !isOwn ? styles$9.tableRowSelectable : "",
                          isOwn ? styles$9.tableRowOwn : "",
                          "tlm-payout-hover-scope"
                        ].filter(Boolean).join(" "),
                        role: "row",
                        "aria-label": `Target ${order.targetUserId}, ${order.escrowedPts.toLocaleString("en-US")} PTS pay${isOwn ? " (your order)" : ""}`,
                        children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.rowCells, children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellSeller}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                              SimpleServiceTargetLink,
                              {
                                targetUserId: order.targetUserId
                              }
                            ) }),
                            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellPay}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                              PayoutValue,
                              {
                                amount: order.escrowedPts,
                                conversion: payoutConversion,
                                label: "References pay"
                              }
                            ) })
                          ] }),
                          !isOwn && !referencesSellBlocked && /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "button",
                            {
                              type: "button",
                              className: styles$9.takeContractBtn,
                              onClick: (e) => {
                                e.stopPropagation();
                                onTakeReferences(order);
                              },
                              children: TAKE_CONTRACT_BUTTON_LABEL
                            }
                          ),
                          isOwn && /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "button",
                            {
                              type: "button",
                              className: styles$9.cancelRedeem,
                              "aria-label": "Cancel references order",
                              onClick: (e) => {
                                e.stopPropagation();
                                onCancelReferences(order);
                              },
                              children: "×"
                            }
                          )
                        ]
                      }
                    );
                  }
                }
              )
            ] })
          ]
        }
      ) : liveOtherSubtype === "bounty-reveal" ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: `${styles$9.table} ${styles$9.tableProductivityBoost}`,
          role: "table",
          "aria-label": "Bounty reveal listings",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHead, role: "rowgroup", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHeaderRow, role: "row", children: SIMPLE_SERVICE_COLUMNS.map(({ id: id2, label: label2 }) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              "span",
              {
                role: "columnheader",
                className: [
                  styles$9.columnHeader,
                  id2 === "pay" ? styles$9.cellPay : ""
                ].filter(Boolean).join(" "),
                children: label2
              },
              id2
            )) }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.tableBody, role: "rowgroup", children: [
              bountyRevealSellBlocked && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.webSellNotice, role: "note", children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("strong", { className: styles$9.webSellNoticeTitle, children: "Selling bounty reveals needs the app" }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { children: [
                  "Bounty listers are pulled from the in-game company special, which the website can't read. Install the",
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "a",
                    {
                      href: CHROME_WEB_STORE_URL,
                      target: "_blank",
                      rel: "noopener noreferrer",
                      children: "Chrome extension"
                    }
                  ),
                  " ",
                  "or the",
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "a",
                    {
                      href: GREASY_FORK_URL,
                      target: "_blank",
                      rel: "noopener noreferrer",
                      children: "userscript"
                    }
                  ),
                  " ",
                  "to fulfill them."
                ] })
              ] }),
              sortedBountyRevealListings.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                MarketListingsEmptyState,
                {
                  message: "No bounty reveal listings yet.",
                  onSetAlert: openAlert,
                  alertThreshold: null,
                  formatAlertThreshold: (value) => value.toLocaleString("en-US")
                }
              ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
                AnimatedList,
                {
                  className: styles$9.list,
                  itemClassName: "tlm-table-row-item",
                  selectOnHover: false,
                  items: sortedBountyRevealListings,
                  getItemKey: (item) => item.id,
                  showGradients: true,
                  enableArrowNavigation: true,
                  displayScrollbar: true,
                  dense: true,
                  listAriaLabel: "Bounty reveal listings",
                  onItemSelect: () => {
                  },
                  renderItem: (order) => {
                    const isOwn = order.buyerXid != null && order.buyerXid === tornXid;
                    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      "div",
                      {
                        className: [
                          styles$9.tableRow,
                          !isOwn ? styles$9.tableRowSelectable : "",
                          isOwn ? styles$9.tableRowOwn : "",
                          "tlm-payout-hover-scope"
                        ].filter(Boolean).join(" "),
                        role: "row",
                        "aria-label": `Target ${order.targetUserId}, ${order.escrowedPts.toLocaleString("en-US")} PTS pay${isOwn ? " (your order)" : ""}`,
                        children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.rowCells, children: [
                            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellSeller}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                              SimpleServiceTargetLink,
                              {
                                targetUserId: order.targetUserId
                              }
                            ) }),
                            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellPay}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                              PayoutValue,
                              {
                                amount: order.escrowedPts,
                                conversion: payoutConversion,
                                label: "Bounty reveal pay"
                              }
                            ) })
                          ] }),
                          !isOwn && !bountyRevealSellBlocked && /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "button",
                            {
                              type: "button",
                              className: styles$9.takeContractBtn,
                              onClick: (e) => {
                                e.stopPropagation();
                                onTakeBountyReveal(order);
                              },
                              children: TAKE_CONTRACT_BUTTON_LABEL
                            }
                          ),
                          isOwn && /* @__PURE__ */ jsxRuntimeExports.jsx(
                            "button",
                            {
                              type: "button",
                              className: styles$9.cancelRedeem,
                              "aria-label": "Cancel bounty reveal order",
                              onClick: (e) => {
                                e.stopPropagation();
                                onCancelBountyReveal(order);
                              },
                              children: "×"
                            }
                          )
                        ]
                      }
                    );
                  }
                }
              )
            ] })
          ]
        }
      ) : activeSimpleServiceKind !== null ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: `${styles$9.table} ${styles$9.tableProductivityBoost}`,
          role: "table",
          "aria-label": `${SIMPLE_SERVICES[activeSimpleServiceKind].label} listings`,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHead, role: "rowgroup", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableHeaderRow, role: "row", children: SIMPLE_SERVICE_COLUMNS.map(({ id: id2, label: label2 }) => /* @__PURE__ */ jsxRuntimeExports.jsx(
              "span",
              {
                role: "columnheader",
                className: [
                  styles$9.columnHeader,
                  id2 === "pay" ? styles$9.cellPay : ""
                ].filter(Boolean).join(" "),
                children: label2
              },
              id2
            )) }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableBody, role: "rowgroup", children: sortedSimpleServiceListings.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx(
              MarketListingsEmptyState,
              {
                message: `No ${SIMPLE_SERVICES[activeSimpleServiceKind].label.toLowerCase()} listings yet.`,
                onSetAlert: openAlert,
                alertThreshold: null,
                formatAlertThreshold: (value) => value.toLocaleString("en-US")
              }
            ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
              AnimatedList,
              {
                className: styles$9.list,
                itemClassName: "tlm-table-row-item",
                selectOnHover: false,
                items: sortedSimpleServiceListings,
                getItemKey: (item) => item.id,
                showGradients: true,
                enableArrowNavigation: true,
                displayScrollbar: true,
                dense: true,
                listAriaLabel: `${SIMPLE_SERVICES[activeSimpleServiceKind].label} listings`,
                onItemSelect: () => {
                },
                renderItem: (service) => {
                  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "div",
                    {
                      className: [
                        styles$9.tableRow,
                        styles$9.tableRowSelectable,
                        styles$9.tableRowOwn,
                        "tlm-payout-hover-scope"
                      ].filter(Boolean).join(" "),
                      role: "row",
                      "aria-label": `Target ${service.targetUserId}, ${service.escrowedPts.toLocaleString("en-US")} PTS pay${" (your order)"}`,
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$9.rowCells, children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellSeller}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                            SimpleServiceTargetLink,
                            {
                              targetUserId: service.targetUserId
                            }
                          ) }),
                          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$9.cell} ${styles$9.cellPay}`, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                            PayoutValue,
                            {
                              amount: service.escrowedPts,
                              conversion: payoutConversion,
                              label: `${SIMPLE_SERVICES[service.kind].label} pay`
                            }
                          ) })
                        ] }),
                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "button",
                          {
                            type: "button",
                            className: styles$9.takeContractBtn,
                            onClick: (e) => {
                              e.stopPropagation();
                              onTakeSimpleService(service);
                            },
                            children: TAKE_CONTRACT_BUTTON_LABEL
                          }
                        ),
                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                          "button",
                          {
                            type: "button",
                            className: styles$9.cancelRedeem,
                            "aria-label": `Cancel ${SIMPLE_SERVICES[service.kind].label.toLowerCase()} order`,
                            onClick: (e) => {
                              e.stopPropagation();
                              onCancelSimpleService(service);
                            },
                            children: "×"
                          }
                        )
                      ]
                    }
                  );
                }
              }
            ) })
          ]
        }
      ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: styles$9.table,
          role: "region",
          "aria-label": `${SERVICE_TYPE_LABELS[activeServiceType]} listings`,
          children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$9.tableBody, role: "rowgroup", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$9.tableComingSoon, children: "Choose a service from the Other menu." }) })
        }
      )
    ] });
  }
  const MARKET_MODES = [
    "selling",
    "buying",
    "redeeming"
  ];
  const MODE_LABELS = {
    selling: "Buy",
    buying: "Sell Attacks",
    redeeming: "Sell Services"
  };
  const pillHidden = "_pillHidden_1kov1_14";
  const pill = "_pill_1kov1_14";
  const pillAlert = "_pillAlert_1kov1_51";
  const segment = "_segment_1kov1_63";
  const segmentAlert = "_segmentAlert_1kov1_94";
  const styles$7 = {
    "switch": "_switch_1kov1_1",
    pillHidden,
    pill,
    pillAlert,
    segment,
    segmentAlert
  };
  function ModeSwitch({
    mode,
    onModeChange,
    alertHighlightedModes,
    sellTabRef,
    buyTabRef
  }) {
    const tablistRef = reactExports.useRef(null);
    const activeIndex = mode === null ? -1 : MARKET_MODES.indexOf(mode);
    const pillVisible = activeIndex >= 0;
    const pillAlert2 = mode !== null && (alertHighlightedModes == null ? void 0 : alertHighlightedModes[mode]) === true;
    const handleKeyDown = reactExports.useCallback(
      (e, index) => {
        var _a2, _b;
        let nextIndex = index;
        if (e.key === "ArrowRight" || e.key === "ArrowDown") {
          e.preventDefault();
          nextIndex = (index + 1) % MARKET_MODES.length;
        } else if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
          e.preventDefault();
          nextIndex = (index - 1 + MARKET_MODES.length) % MARKET_MODES.length;
        } else if (e.key === "Home") {
          e.preventDefault();
          nextIndex = 0;
        } else if (e.key === "End") {
          e.preventDefault();
          nextIndex = MARKET_MODES.length - 1;
        } else {
          return;
        }
        onModeChange(MARKET_MODES[nextIndex]);
        const tabs2 = (_a2 = tablistRef.current) == null ? void 0 : _a2.querySelectorAll(
          '[role="tab"]'
        );
        (_b = tabs2 == null ? void 0 : tabs2[nextIndex]) == null ? void 0 : _b.focus();
      },
      [onModeChange]
    );
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "div",
      {
        ref: tablistRef,
        className: styles$7.switch,
        role: "tablist",
        "aria-label": "Marketplace mode",
        children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: `${styles$7.pill} ${pillVisible ? "" : styles$7.pillHidden} ${pillAlert2 ? styles$7.pillAlert : ""}`,
              style: pillVisible ? { transform: `translateX(${activeIndex * 100}%)` } : void 0,
              "aria-hidden": "true"
            }
          ),
          MARKET_MODES.map((m, index) => {
            const selected = m === mode;
            const alertHighlighted = (alertHighlightedModes == null ? void 0 : alertHighlightedModes[m]) === true;
            return /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                type: "button",
                role: "tab",
                id: `tlm-tab-${m}`,
                ref: m === "buying" ? sellTabRef : m === "selling" ? buyTabRef : void 0,
                "aria-selected": selected,
                "aria-controls": `tlm-panel-${m}`,
                tabIndex: selected ? 0 : -1,
                className: `${styles$7.segment} ${alertHighlighted ? styles$7.segmentAlert : ""}`,
                onClick: () => onModeChange(m),
                onKeyDown: (e) => handleKeyDown(e, index),
                children: MODE_LABELS[m]
              },
              m
            );
          })
        ]
      }
    );
  }
  function keyFor(group2) {
    return `settings_group_open_${group2}`;
  }
  function readSettingsGroupOpen(group2) {
    try {
      const raw = readLocalStorageWithMigration(localStorage, keyFor(group2));
      if (raw === "false") return false;
      if (raw === "true") return true;
    } catch {
    }
    return true;
  }
  function writeSettingsGroupOpen(group2, open) {
    try {
      writeLocalStorageCurrent(localStorage, keyFor(group2), open ? "true" : "false");
    } catch {
    }
  }
  const panel$1 = "_panel_319qe_1";
  const section = "_section_319qe_10";
  const sectionHeading = "_sectionHeading_319qe_20";
  const fieldLabel = "_fieldLabel_319qe_28";
  const alertFields = "_alertFields_319qe_38";
  const field = "_field_319qe_28";
  const alertThresholdTable = "_alertThresholdTable_319qe_48";
  const alertThresholdHeader = "_alertThresholdHeader_319qe_54";
  const alertThresholdRow = "_alertThresholdRow_319qe_66";
  const alertThresholdLabel = "_alertThresholdLabel_319qe_73";
  const alertThresholdInput = "_alertThresholdInput_319qe_79";
  const alertInputError = "_alertInputError_319qe_172";
  const alertHint = "_alertHint_319qe_176";
  const alertError = "_alertError_319qe_183";
  const alertConfirm = "_alertConfirm_319qe_190";
  const volumeRow$1 = "_volumeRow_319qe_222";
  const volumeControl = "_volumeControl_319qe_226";
  const volumeSlider$1 = "_volumeSlider_319qe_233";
  const volumeValue$1 = "_volumeValue_319qe_252";
  const fieldList = "_fieldList_319qe_262";
  const mono = "_mono_319qe_291";
  const apiKeyRow = "_apiKeyRow_319qe_296";
  const apiKeyValue = "_apiKeyValue_319qe_302";
  const eyeButton = "_eyeButton_319qe_310";
  const actions$1 = "_actions_319qe_340";
  const logoutButton = "_logoutButton_319qe_349";
  const deleteAccountButton = "_deleteAccountButton_319qe_350";
  const connectButton = "_connectButton_319qe_351";
  const viewArchiveButton = "_viewArchiveButton_319qe_404";
  const legalFooter = "_legalFooter_319qe_441";
  const versionLabel = "_versionLabel_319qe_450";
  const legalLink = "_legalLink_319qe_457";
  const legalSep = "_legalSep_319qe_473";
  const alertGroup = "_alertGroup_319qe_478";
  const alertGroupHeader = "_alertGroupHeader_319qe_484";
  const alertGroupChevron = "_alertGroupChevron_319qe_514";
  const alertGroupChevronOpen = "_alertGroupChevronOpen_319qe_520";
  const alertGroupBody = "_alertGroupBody_319qe_524";
  const alertGroupCollapsedBadges = "_alertGroupCollapsedBadges_319qe_530";
  const alertCollapsedBadge = "_alertCollapsedBadge_319qe_536";
  const alertCollapsedBadgeActive = "_alertCollapsedBadgeActive_319qe_567";
  const styles$6 = {
    panel: panel$1,
    section,
    sectionHeading,
    fieldLabel,
    alertFields,
    field,
    alertThresholdTable,
    alertThresholdHeader,
    alertThresholdRow,
    alertThresholdLabel,
    alertThresholdInput,
    alertInputError,
    alertHint,
    alertError,
    alertConfirm,
    volumeRow: volumeRow$1,
    volumeControl,
    volumeSlider: volumeSlider$1,
    volumeValue: volumeValue$1,
    fieldList,
    mono,
    apiKeyRow,
    apiKeyValue,
    eyeButton,
    actions: actions$1,
    logoutButton,
    deleteAccountButton,
    connectButton,
    viewArchiveButton,
    legalFooter,
    versionLabel,
    legalLink,
    legalSep,
    alertGroup,
    alertGroupHeader,
    alertGroupChevron,
    alertGroupChevronOpen,
    alertGroupBody,
    alertGroupCollapsedBadges,
    alertCollapsedBadge,
    alertCollapsedBadgeActive
  };
  const MARKET_ALERT_TYPES = CONTRACT_TYPES;
  function maskApiKey(key) {
    if (key.length <= 4) return "••••••••••••••••";
    return `${"•".repeat(12)}${key.slice(-4)}`;
  }
  function SettingsPanel({
    session,
    tornXid,
    alerts,
    onLogout,
    onRequestDeleteAccount,
    onConnect,
    onOpenReferrals,
    onViewArchive,
    archiveCount = 0,
    deletingAccount = false,
    balance
  }) {
    var _a2;
    const {
      alertThreshold,
      onAlertThresholdChange,
      alertEscapeThreshold,
      onAlertEscapeThresholdChange,
      alertStalemateThreshold,
      onAlertStalemateThresholdChange,
      alertWithdrawalThreshold,
      onAlertWithdrawalThresholdChange,
      alertBountyThreshold,
      onAlertBountyThresholdChange,
      alertEmbargoThreshold,
      onAlertEmbargoThresholdChange,
      alertProductivityThreshold,
      onAlertProductivityThresholdChange,
      alertFlightDelayThreshold,
      onAlertFlightDelayThresholdChange,
      alertSimpleServiceThresholds,
      onAlertSimpleServiceThresholdChange,
      alertVolume,
      onAlertVolumeChange
    } = alerts;
    const platform = getPlatformRuntime();
    const lossesAlertInputId = reactExports.useId();
    const escapesAlertInputId = reactExports.useId();
    const stalematesAlertInputId = reactExports.useId();
    const withdrawalInputId = reactExports.useId();
    const bountyInputId = reactExports.useId();
    const embargoInputId = reactExports.useId();
    const productivityInputId = reactExports.useId();
    const flightDelayInputId = reactExports.useId();
    const alertVolumeId = reactExports.useId();
    const marketAlertInputIds = {
      losses: lossesAlertInputId,
      escapes: escapesAlertInputId,
      stalemates: stalematesAlertInputId
    };
    const [apiKey, setApiKey] = reactExports.useState(null);
    const [apiKeyLoading, setApiKeyLoading] = reactExports.useState(false);
    const [apiKeyVisible, setApiKeyVisible] = reactExports.useState(false);
    const [loggingOut, setLoggingOut] = reactExports.useState(false);
    const marketAlerts = [
      {
        type: "losses",
        value: alertThreshold,
        onChange: onAlertThresholdChange
      },
      {
        type: "escapes",
        value: alertEscapeThreshold,
        onChange: onAlertEscapeThresholdChange
      },
      {
        type: "stalemates",
        value: alertStalemateThreshold,
        onChange: onAlertStalemateThresholdChange
      }
    ];
    const [marketThresholdInputs, setMarketThresholdInputs] = reactExports.useState(
      () => Object.fromEntries(
        marketAlerts.map(({ type, value }) => [type, thresholdToInput(value)])
      )
    );
    const [marketThresholdErrors, setMarketThresholdErrors] = reactExports.useState({
      losses: null,
      escapes: null,
      stalemates: null
    });
    const [withdrawalInput, setWithdrawalInput] = reactExports.useState(
      () => thresholdToInput(alertWithdrawalThreshold)
    );
    const [withdrawalError, setWithdrawalError] = reactExports.useState(null);
    const [bountyInput, setBountyInput] = reactExports.useState(
      () => thresholdToInput(alertBountyThreshold)
    );
    const [bountyError, setBountyError] = reactExports.useState(null);
    const [embargoInput, setEmbargoInput] = reactExports.useState(
      () => thresholdToInput(alertEmbargoThreshold)
    );
    const [embargoError, setEmbargoError] = reactExports.useState(null);
    const [productivityInput, setProductivityInput] = reactExports.useState(
      () => thresholdToInput(alertProductivityThreshold)
    );
    const [productivityError, setProductivityError] = reactExports.useState(
      null
    );
    const [flightDelayInput, setFlightDelayInput] = reactExports.useState(
      () => thresholdToInput(alertFlightDelayThreshold)
    );
    const [flightDelayError, setFlightDelayError] = reactExports.useState(
      null
    );
    const [simpleServiceInputs, setSimpleServiceInputs] = reactExports.useState(
      () => Object.fromEntries(
        SIMPLE_SERVICE_IDS.map((kind) => [
          kind,
          thresholdToInput(alertSimpleServiceThresholds[kind])
        ])
      )
    );
    const [simpleServiceErrors, setSimpleServiceErrors] = reactExports.useState(
      () => Object.fromEntries(
        SIMPLE_SERVICE_IDS.map((kind) => [kind, null])
      )
    );
    const [sellGroupOpen, setSellGroupOpen] = reactExports.useState(
      () => readSettingsGroupOpen("sell_attacks")
    );
    const [sellServicesGroupOpen, setSellServicesGroupOpen] = reactExports.useState(
      () => readSettingsGroupOpen("sell_services")
    );
    reactExports.useEffect(() => {
      writeSettingsGroupOpen("sell_attacks", sellGroupOpen);
    }, [sellGroupOpen]);
    reactExports.useEffect(() => {
      writeSettingsGroupOpen("sell_services", sellServicesGroupOpen);
    }, [sellServicesGroupOpen]);
    reactExports.useEffect(() => {
      setMarketThresholdInputs({
        losses: thresholdToInput(alertThreshold),
        escapes: thresholdToInput(alertEscapeThreshold),
        stalemates: thresholdToInput(alertStalemateThreshold)
      });
      setMarketThresholdErrors({
        losses: null,
        escapes: null,
        stalemates: null
      });
    }, [
      alertThreshold,
      alertEscapeThreshold,
      alertStalemateThreshold,
      tornXid
    ]);
    reactExports.useEffect(() => {
      setWithdrawalInput(thresholdToInput(alertWithdrawalThreshold));
      setWithdrawalError(null);
    }, [alertWithdrawalThreshold, tornXid]);
    reactExports.useEffect(() => {
      setBountyInput(thresholdToInput(alertBountyThreshold));
      setBountyError(null);
    }, [alertBountyThreshold, tornXid]);
    reactExports.useEffect(() => {
      setEmbargoInput(thresholdToInput(alertEmbargoThreshold));
      setEmbargoError(null);
    }, [alertEmbargoThreshold, tornXid]);
    reactExports.useEffect(() => {
      setProductivityInput(thresholdToInput(alertProductivityThreshold));
      setProductivityError(null);
    }, [alertProductivityThreshold, tornXid]);
    reactExports.useEffect(() => {
      setFlightDelayInput(thresholdToInput(alertFlightDelayThreshold));
      setFlightDelayError(null);
    }, [alertFlightDelayThreshold, tornXid]);
    reactExports.useEffect(() => {
      setSimpleServiceInputs(
        Object.fromEntries(
          SIMPLE_SERVICE_IDS.map((kind) => [
            kind,
            thresholdToInput(alertSimpleServiceThresholds[kind])
          ])
        )
      );
      setSimpleServiceErrors(
        Object.fromEntries(
          SIMPLE_SERVICE_IDS.map((kind) => [kind, null])
        )
      );
    }, [alertSimpleServiceThresholds, tornXid]);
    reactExports.useEffect(() => {
      if (!session) {
        setApiKey(null);
        return;
      }
      let cancelled = false;
      setApiKeyLoading(true);
      void platform.auth.getApiKey().then((key) => {
        if (cancelled) return;
        setApiKey(key);
        setApiKeyLoading(false);
      }).catch(() => {
        if (cancelled) return;
        setApiKey(null);
        setApiKeyLoading(false);
      });
      return () => {
        cancelled = true;
      };
    }, [platform, session == null ? void 0 : session.torn_xid]);
    const displayName = ((_a2 = session == null ? void 0 : session.display_name) == null ? void 0 : _a2.trim()) || (session ? "Unknown" : "—");
    const tornId = session ? String(session.torn_xid) : "—";
    const apiKeyDisplay = (() => {
      if (!session) return "Not connected";
      if (apiKeyLoading) return "Loading…";
      if (!apiKey) return "Not stored in this extension";
      return apiKeyVisible ? apiKey : maskApiKey(apiKey);
    })();
    const handleLogout = () => {
      setLoggingOut(true);
      void Promise.resolve(onLogout()).finally(() => {
        setLoggingOut(false);
        setApiKeyVisible(false);
      });
    };
    const previewAlertSound = () => {
      playLossMarketAlertSound(alertVolume);
    };
    const commitMarketThreshold = (type) => {
      var _a3;
      const input2 = marketThresholdInputs[type];
      const onChange = (_a3 = marketAlerts.find((alert) => alert.type === type)) == null ? void 0 : _a3.onChange;
      if (!onChange) return false;
      const trimmed = input2.trim();
      if (!trimmed) {
        setMarketThresholdErrors((prev) => ({ ...prev, [type]: null }));
        onChange(null);
        return false;
      }
      const rawValue = evaluateNumericInput(trimmed);
      if (rawValue === 0) {
        setMarketThresholdErrors((prev) => ({ ...prev, [type]: null }));
        setMarketThresholdInputs((prev) => ({ ...prev, [type]: "" }));
        onChange(null);
        return false;
      }
      const message = getPayAlertValidationMessage(input2, type);
      if (message) {
        setMarketThresholdErrors((prev) => ({ ...prev, [type]: message }));
        return false;
      }
      const parsed = parsePriceInput(input2);
      if (parsed === null) {
        setMarketThresholdErrors((prev) => ({
          ...prev,
          [type]: `Enter a valid price (${formatExtensionPoints(BUYER_ORDER_PRICE_MIN)}–${formatExtensionPoints(BUYER_ORDER_PRICE_MAX)}, optional k/m/b).`
        }));
        return false;
      }
      setMarketThresholdErrors((prev) => ({ ...prev, [type]: null }));
      setMarketThresholdInputs((prev) => ({
        ...prev,
        [type]: thresholdToInput(parsed)
      }));
      onChange(parsed);
      return true;
    };
    const commitPayThreshold = () => MARKET_ALERT_TYPES.some((type) => commitMarketThreshold(type));
    const commitWithdrawalThreshold = () => {
      const trimmed = withdrawalInput.trim();
      if (!trimmed) {
        setWithdrawalError(null);
        onAlertWithdrawalThresholdChange(null);
        return false;
      }
      const rawValue = evaluateNumericInput(trimmed);
      if (rawValue === 0) {
        setWithdrawalError(null);
        setWithdrawalInput("");
        onAlertWithdrawalThresholdChange(null);
        return false;
      }
      const message = getQuantityAlertValidationMessage(
        withdrawalInput,
        "Withdrawal"
      );
      if (message) {
        setWithdrawalError(message);
        return false;
      }
      const parsed = parseQuantityInput(withdrawalInput);
      if (parsed === null) {
        setWithdrawalError(
          `Enter a valid quantity (${ALERT_WITHDRAWAL_QTY_MIN}–${ALERT_WITHDRAWAL_QTY_MAX.toLocaleString("en-US")}, optional k/m/b).`
        );
        return false;
      }
      setWithdrawalError(null);
      setWithdrawalInput(thresholdToInput(parsed));
      onAlertWithdrawalThresholdChange(parsed);
      return true;
    };
    const commitBountyThreshold = () => {
      const trimmed = bountyInput.trim();
      if (!trimmed) {
        setBountyError(null);
        onAlertBountyThresholdChange(null);
        return false;
      }
      const rawValue = evaluateNumericInput(trimmed);
      if (rawValue === 0) {
        setBountyError(null);
        setBountyInput("");
        onAlertBountyThresholdChange(null);
        return false;
      }
      const message = getQuantityAlertValidationMessage(bountyInput, "Bounty");
      if (message) {
        setBountyError(message);
        return false;
      }
      const parsed = parseQuantityInput(bountyInput);
      if (parsed === null) {
        setBountyError(
          `Enter a valid quantity (${ALERT_WITHDRAWAL_QTY_MIN}–${ALERT_WITHDRAWAL_QTY_MAX.toLocaleString("en-US")}, optional k/m/b).`
        );
        return false;
      }
      setBountyError(null);
      setBountyInput(thresholdToInput(parsed));
      onAlertBountyThresholdChange(parsed);
      return true;
    };
    const commitEmbargoThreshold = () => {
      const trimmed = embargoInput.trim();
      if (!trimmed) {
        setEmbargoError(null);
        onAlertEmbargoThresholdChange(null);
        return false;
      }
      const rawValue = evaluateNumericInput(trimmed);
      if (rawValue === 0) {
        setEmbargoError(null);
        setEmbargoInput("");
        onAlertEmbargoThresholdChange(null);
        return false;
      }
      const message = getPayAlertValidationMessage(embargoInput, "losses");
      if (message) {
        setEmbargoError(message);
        return false;
      }
      const parsed = parsePriceInput(embargoInput);
      if (parsed === null) {
        setEmbargoError(
          `Enter a valid price (${formatExtensionPoints(BUYER_ORDER_PRICE_MIN)}–${formatExtensionPoints(BUYER_ORDER_PRICE_MAX)}, optional k/m/b).`
        );
        return false;
      }
      setEmbargoError(null);
      setEmbargoInput(thresholdToInput(parsed));
      onAlertEmbargoThresholdChange(parsed);
      return true;
    };
    const commitProductivityThreshold = () => {
      const trimmed = productivityInput.trim();
      if (!trimmed) {
        setProductivityError(null);
        onAlertProductivityThresholdChange(null);
        return false;
      }
      const rawValue = evaluateNumericInput(trimmed);
      if (rawValue === 0) {
        setProductivityError(null);
        setProductivityInput("");
        onAlertProductivityThresholdChange(null);
        return false;
      }
      const message = getPayAlertValidationMessage(productivityInput, "losses");
      if (message) {
        setProductivityError(message);
        return false;
      }
      const parsed = parsePriceInput(productivityInput);
      if (parsed === null) {
        setProductivityError(
          `Enter a valid price (${formatExtensionPoints(BUYER_ORDER_PRICE_MIN)}–${formatExtensionPoints(BUYER_ORDER_PRICE_MAX)}, optional k/m/b).`
        );
        return false;
      }
      setProductivityError(null);
      setProductivityInput(thresholdToInput(parsed));
      onAlertProductivityThresholdChange(parsed);
      return true;
    };
    const commitFlightDelayThreshold = () => {
      const trimmed = flightDelayInput.trim();
      if (!trimmed) {
        setFlightDelayError(null);
        onAlertFlightDelayThresholdChange(null);
        return false;
      }
      const rawValue = evaluateNumericInput(trimmed);
      if (rawValue === 0) {
        setFlightDelayError(null);
        setFlightDelayInput("");
        onAlertFlightDelayThresholdChange(null);
        return false;
      }
      const message = getPayAlertValidationMessage(flightDelayInput, "losses");
      if (message) {
        setFlightDelayError(message);
        return false;
      }
      const parsed = parsePriceInput(flightDelayInput);
      if (parsed === null) {
        setFlightDelayError(
          `Enter a valid price (${formatExtensionPoints(BUYER_ORDER_PRICE_MIN)}–${formatExtensionPoints(BUYER_ORDER_PRICE_MAX)}, optional k/m/b).`
        );
        return false;
      }
      setFlightDelayError(null);
      setFlightDelayInput(thresholdToInput(parsed));
      onAlertFlightDelayThresholdChange(parsed);
      return true;
    };
    const commitSimpleServiceThreshold = (kind) => {
      const input2 = simpleServiceInputs[kind];
      const trimmed = input2.trim();
      if (!trimmed) {
        setSimpleServiceErrors((prev) => ({ ...prev, [kind]: null }));
        onAlertSimpleServiceThresholdChange(kind, null);
        return false;
      }
      const rawValue = evaluateNumericInput(trimmed);
      if (rawValue === 0) {
        setSimpleServiceErrors((prev) => ({ ...prev, [kind]: null }));
        setSimpleServiceInputs((prev) => ({ ...prev, [kind]: "" }));
        onAlertSimpleServiceThresholdChange(kind, null);
        return false;
      }
      const message = getPayAlertValidationMessage(input2, "losses");
      if (message) {
        setSimpleServiceErrors((prev) => ({ ...prev, [kind]: message }));
        return false;
      }
      const parsed = parsePriceInput(input2);
      if (parsed === null) {
        setSimpleServiceErrors((prev) => ({
          ...prev,
          [kind]: `Enter a valid price (${formatExtensionPoints(BUYER_ORDER_PRICE_MIN)}–${formatExtensionPoints(BUYER_ORDER_PRICE_MAX)}, optional k/m/b).`
        }));
        return false;
      }
      setSimpleServiceErrors((prev) => ({ ...prev, [kind]: null }));
      setSimpleServiceInputs((prev) => ({
        ...prev,
        [kind]: thresholdToInput(parsed)
      }));
      onAlertSimpleServiceThresholdChange(kind, parsed);
      return true;
    };
    const commitAlertSettings = () => {
      const payOk = commitPayThreshold();
      const withdrawalOk = commitWithdrawalThreshold();
      const bountyOk = commitBountyThreshold();
      const embargoOk = commitEmbargoThreshold();
      const productivityOk = commitProductivityThreshold();
      const flightDelayOk = commitFlightDelayThreshold();
      const simpleServiceOk = SIMPLE_SERVICE_IDS.map(
        (kind) => commitSimpleServiceThreshold(kind)
      ).some(Boolean);
      if (payOk || withdrawalOk || bountyOk || embargoOk || productivityOk || flightDelayOk || simpleServiceOk) {
        previewAlertSound();
      }
    };
    const [alertCommitTick, setAlertCommitTick] = reactExports.useState(0);
    const requestAlertCommit = () => setAlertCommitTick((t) => t + 1);
    reactExports.useEffect(() => {
      if (alertCommitTick === 0) return;
      commitAlertSettings();
    }, [alertCommitTick]);
    const firstMarketAlertError = MARKET_ALERT_TYPES.map(
      (type) => marketThresholdErrors[type]
    ).find(Boolean);
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.panel, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("section", { className: styles$6.section, "aria-label": "Alert", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: styles$6.sectionHeading, children: "Alert" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.alertFields, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.alertGroup, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "button",
              {
                type: "button",
                className: styles$6.alertGroupHeader,
                "aria-expanded": sellGroupOpen,
                onClick: () => setSellGroupOpen((open) => !open),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Sell Attacks" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    ChevronRight,
                    {
                      size: 14,
                      "aria-hidden": true,
                      className: `${styles$6.alertGroupChevron} ${sellGroupOpen ? styles$6.alertGroupChevronOpen : ""}`
                    }
                  )
                ]
              }
            ),
            sellGroupOpen ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$6.alertGroupBody, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.alertThresholdTable, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "div",
                {
                  className: styles$6.alertThresholdHeader,
                  "aria-hidden": "true",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Attacks" }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "At or above" })
                  ]
                }
              ),
              MARKET_ALERT_TYPES.map((type) => {
                const inputId = marketAlertInputIds[type];
                const error2 = marketThresholdErrors[type];
                const singular = CONTRACT_TYPE_SINGULAR[type].toLowerCase();
                return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.alertThresholdRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "label",
                    {
                      className: styles$6.alertThresholdLabel,
                      htmlFor: inputId,
                      children: CONTRACT_TYPE_LABELS[type]
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    PtsAmountInput,
                    {
                      id: inputId,
                      value: marketThresholdInputs[type],
                      onChange: (next) => {
                        setMarketThresholdInputs((prev) => ({
                          ...prev,
                          [type]: next
                        }));
                        setMarketThresholdErrors((prev) => ({
                          ...prev,
                          [type]: null
                        }));
                      },
                      onEnter: requestAlertCommit,
                      max: BUYER_ORDER_PRICE_MAX,
                      referenceMax: balance,
                      sanitize: sanitizePriceInput,
                      inputMode: "decimal",
                      placeholder: `Pay / ${singular}`,
                      ariaLabel: `Pay per ${singular} at or above`,
                      disabled: tornXid === null,
                      hasError: Boolean(error2)
                    }
                  )
                ] }, type);
              })
            ] }) }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.alertGroupCollapsedBadges, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  className: `${styles$6.alertCollapsedBadge} ${alertThreshold !== null ? styles$6.alertCollapsedBadgeActive : ""}`,
                  "aria-label": "Expand Sell alerts (Losses)",
                  onClick: () => setSellGroupOpen(true),
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(Skull, { size: 14, "aria-hidden": true })
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  className: `${styles$6.alertCollapsedBadge} ${alertEscapeThreshold !== null ? styles$6.alertCollapsedBadgeActive : ""}`,
                  "aria-label": "Expand Sell alerts (Escapes)",
                  onClick: () => setSellGroupOpen(true),
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(Wind, { size: 14, "aria-hidden": true })
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  className: `${styles$6.alertCollapsedBadge} ${alertStalemateThreshold !== null ? styles$6.alertCollapsedBadgeActive : ""}`,
                  "aria-label": "Expand Sell alerts (Stalemates)",
                  onClick: () => setSellGroupOpen(true),
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(Shield, { size: 14, "aria-hidden": true })
                }
              )
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.alertGroup, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "button",
              {
                type: "button",
                className: styles$6.alertGroupHeader,
                "aria-expanded": sellServicesGroupOpen,
                onClick: () => setSellServicesGroupOpen((open) => !open),
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Sell services" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    ChevronRight,
                    {
                      size: 14,
                      "aria-hidden": true,
                      className: `${styles$6.alertGroupChevron} ${sellServicesGroupOpen ? styles$6.alertGroupChevronOpen : ""}`
                    }
                  )
                ]
              }
            ),
            sellServicesGroupOpen ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.alertGroupBody, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "div",
                {
                  className: styles$6.alertThresholdHeader,
                  "aria-hidden": "true",
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "Services" }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: "At or above" })
                  ]
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.alertThresholdRow, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    className: styles$6.alertThresholdLabel,
                    htmlFor: withdrawalInputId,
                    children: "Withdrawals"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "input",
                  {
                    id: withdrawalInputId,
                    className: `${styles$6.alertThresholdInput} ${withdrawalError ? styles$6.alertInputError : ""}`,
                    type: "text",
                    inputMode: "numeric",
                    placeholder: "Quantity",
                    value: withdrawalInput,
                    disabled: tornXid === null,
                    "aria-label": "Withdrawal quantity at or above",
                    onChange: (e) => {
                      setWithdrawalInput(sanitizeQuantityInput(e.target.value));
                      setWithdrawalError(null);
                    },
                    onKeyDown: (e) => {
                      if (e.key === "Enter") {
                        e.preventDefault();
                        commitAlertSettings();
                      }
                    }
                  }
                )
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.alertThresholdRow, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    className: styles$6.alertThresholdLabel,
                    htmlFor: bountyInputId,
                    children: "Bounties"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "input",
                  {
                    id: bountyInputId,
                    className: `${styles$6.alertThresholdInput} ${bountyError ? styles$6.alertInputError : ""}`,
                    type: "text",
                    inputMode: "numeric",
                    placeholder: "Quantity",
                    value: bountyInput,
                    disabled: tornXid === null,
                    "aria-label": "Bounty quantity at or above",
                    onChange: (e) => {
                      setBountyInput(sanitizeQuantityInput(e.target.value));
                      setBountyError(null);
                    },
                    onKeyDown: (e) => {
                      if (e.key === "Enter") {
                        e.preventDefault();
                        commitAlertSettings();
                      }
                    }
                  }
                )
              ] }),
              isServiceActionEnabled("embargo") && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.alertThresholdRow, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    className: styles$6.alertThresholdLabel,
                    htmlFor: embargoInputId,
                    children: "Embargo"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  PtsAmountInput,
                  {
                    id: embargoInputId,
                    value: embargoInput,
                    onChange: (next) => {
                      setEmbargoInput(next);
                      setEmbargoError(null);
                    },
                    onEnter: requestAlertCommit,
                    max: BUYER_ORDER_PRICE_MAX,
                    referenceMax: balance,
                    sanitize: sanitizePriceInput,
                    inputMode: "decimal",
                    placeholder: "Pay",
                    ariaLabel: "Embargo pay at or above",
                    disabled: tornXid === null,
                    hasError: Boolean(embargoError)
                  }
                )
              ] }),
              isServiceActionEnabled("productivity") && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.alertThresholdRow, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    className: styles$6.alertThresholdLabel,
                    htmlFor: productivityInputId,
                    children: "Productivity"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  PtsAmountInput,
                  {
                    id: productivityInputId,
                    value: productivityInput,
                    onChange: (next) => {
                      setProductivityInput(next);
                      setProductivityError(null);
                    },
                    onEnter: requestAlertCommit,
                    max: BUYER_ORDER_PRICE_MAX,
                    referenceMax: balance,
                    sanitize: sanitizePriceInput,
                    inputMode: "decimal",
                    placeholder: "Pay",
                    ariaLabel: "Productivity boost pay at or above",
                    disabled: tornXid === null,
                    hasError: Boolean(productivityError)
                  }
                )
              ] }),
              isServiceActionEnabled("flight-delay") && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.alertThresholdRow, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "label",
                  {
                    className: styles$6.alertThresholdLabel,
                    htmlFor: flightDelayInputId,
                    children: "Flight delay"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  PtsAmountInput,
                  {
                    id: flightDelayInputId,
                    value: flightDelayInput,
                    onChange: (next) => {
                      setFlightDelayInput(next);
                      setFlightDelayError(null);
                    },
                    onEnter: requestAlertCommit,
                    max: BUYER_ORDER_PRICE_MAX,
                    referenceMax: balance,
                    sanitize: sanitizePriceInput,
                    inputMode: "decimal",
                    placeholder: "Pay",
                    ariaLabel: "Flight delay pay at or above",
                    disabled: tornXid === null,
                    hasError: Boolean(flightDelayError)
                  }
                )
              ] }),
              SIMPLE_SERVICE_IDS.filter(
                (kind) => isServiceActionEnabled(kind)
              ).map((kind) => {
                const config = SIMPLE_SERVICES[kind];
                const inputId = `tlm-alert-simple-${kind}`;
                const error2 = simpleServiceErrors[kind];
                return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.alertThresholdRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "label",
                    {
                      className: styles$6.alertThresholdLabel,
                      htmlFor: inputId,
                      children: config.label
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    PtsAmountInput,
                    {
                      id: inputId,
                      value: simpleServiceInputs[kind],
                      onChange: (next) => {
                        setSimpleServiceInputs((prev) => ({
                          ...prev,
                          [kind]: next
                        }));
                        setSimpleServiceErrors((prev) => ({
                          ...prev,
                          [kind]: null
                        }));
                      },
                      onEnter: requestAlertCommit,
                      max: BUYER_ORDER_PRICE_MAX,
                      referenceMax: balance,
                      sanitize: sanitizePriceInput,
                      inputMode: "decimal",
                      placeholder: "Pay",
                      ariaLabel: `${config.label} pay at or above`,
                      disabled: tornXid === null,
                      hasError: Boolean(error2)
                    }
                  )
                ] }, kind);
              })
            ] }) : /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.alertGroupCollapsedBadges, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  className: `${styles$6.alertCollapsedBadge} ${alertWithdrawalThreshold !== null ? styles$6.alertCollapsedBadgeActive : ""}`,
                  "aria-label": "Expand Sell services alerts (Withdrawals)",
                  onClick: () => setSellServicesGroupOpen(true),
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(Pill, { size: 14, "aria-hidden": true })
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  className: `${styles$6.alertCollapsedBadge} ${alertBountyThreshold !== null ? styles$6.alertCollapsedBadgeActive : ""}`,
                  "aria-label": "Expand Sell services alerts (Bounties)",
                  onClick: () => setSellServicesGroupOpen(true),
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(Crosshair, { size: 14, "aria-hidden": true })
                }
              ),
              isServiceActionEnabled("embargo") && /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  className: `${styles$6.alertCollapsedBadge} ${alertEmbargoThreshold !== null ? styles$6.alertCollapsedBadgeActive : ""}`,
                  "aria-label": "Expand Sell services alerts (Embargo)",
                  onClick: () => setSellServicesGroupOpen(true),
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(Frown, { size: 14, "aria-hidden": true })
                }
              ),
              isServiceActionEnabled("productivity") && /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  className: `${styles$6.alertCollapsedBadge} ${alertProductivityThreshold !== null ? styles$6.alertCollapsedBadgeActive : ""}`,
                  "aria-label": "Expand Sell services alerts (Productivity)",
                  onClick: () => setSellServicesGroupOpen(true),
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(Building2, { size: 14, "aria-hidden": true })
                }
              ),
              isServiceActionEnabled("flight-delay") && /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  className: `${styles$6.alertCollapsedBadge} ${alertFlightDelayThreshold !== null ? styles$6.alertCollapsedBadgeActive : ""}`,
                  "aria-label": "Expand Sell services alerts (Flight delay)",
                  onClick: () => setSellServicesGroupOpen(true),
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(PlaneTakeoff, { size: 14, "aria-hidden": true })
                }
              ),
              SIMPLE_SERVICE_IDS.filter(
                (kind) => isServiceActionEnabled(kind)
              ).map((kind) => {
                const config = SIMPLE_SERVICES[kind];
                const Icon2 = config.Icon;
                const active = alertSimpleServiceThresholds[kind] !== null;
                return /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: `${styles$6.alertCollapsedBadge} ${active ? styles$6.alertCollapsedBadgeActive : ""}`,
                    "aria-label": `Expand Sell services alerts (${config.label})`,
                    onClick: () => setSellServicesGroupOpen(true),
                    children: /* @__PURE__ */ jsxRuntimeExports.jsx(Icon2, { size: 14, "aria-hidden": true })
                  },
                  kind
                );
              })
            ] })
          ] }),
          (firstMarketAlertError || withdrawalError || bountyError || embargoError || productivityError || flightDelayError || SIMPLE_SERVICE_IDS.some((kind) => simpleServiceErrors[kind])) && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$6.alertError, role: "alert", children: firstMarketAlertError ?? withdrawalError ?? bountyError ?? embargoError ?? productivityError ?? flightDelayError ?? SIMPLE_SERVICE_IDS.map(
            (kind) => simpleServiceErrors[kind]
          ).find(Boolean) }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.volumeRow, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: styles$6.fieldLabel, htmlFor: alertVolumeId, children: "Sound volume" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.volumeControl, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "input",
                {
                  id: alertVolumeId,
                  className: styles$6.volumeSlider,
                  type: "range",
                  min: 0,
                  max: 100,
                  step: 1,
                  value: alertVolume,
                  disabled: tornXid === null,
                  "aria-valuemin": 0,
                  "aria-valuemax": 100,
                  "aria-valuenow": alertVolume,
                  "aria-valuetext": `${alertVolume}%`,
                  onChange: (e) => {
                    onAlertVolumeChange(Number(e.target.value));
                  }
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$6.volumeValue, children: [
                alertVolume,
                "%"
              ] })
            ] })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: styles$6.alertConfirm,
              onClick: commitAlertSettings,
              disabled: tornXid === null,
              children: "Confirm"
            }
          ),
          tornXid === null ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$6.alertHint, children: "Connect your API key to save alert settings." }) : /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$6.alertHint, children: "Panel button turns red and plays a sound when a listing matches your thresholds." })
        ] })
      ] }),
      session && onViewArchive && /* @__PURE__ */ jsxRuntimeExports.jsx("section", { className: styles$6.section, "aria-label": "Archive", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          className: styles$6.viewArchiveButton,
          onClick: onViewArchive,
          children: [
            "View Archive",
            archiveCount > 0 ? ` (${archiveCount})` : ""
          ]
        }
      ) }),
      session && onOpenReferrals && /* @__PURE__ */ jsxRuntimeExports.jsx("section", { className: styles$6.section, "aria-label": "Referrals", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          className: styles$6.connectButton,
          onClick: onOpenReferrals,
          children: "Make 100k Per Referral!"
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("section", { className: styles$6.section, "aria-label": "Settings", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: styles$6.sectionHeading, children: "Settings" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("dl", { className: styles$6.fieldList, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.field, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "Username" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { children: displayName })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.field, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "Torn ID" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { className: styles$6.mono, children: tornId })
          ] }),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$6.field, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: "API key" }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("dd", { className: styles$6.apiKeyRow, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$6.apiKeyValue, "aria-live": "polite", children: apiKeyDisplay }),
              session && apiKey && !apiKeyLoading && /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  className: styles$6.eyeButton,
                  onClick: () => setApiKeyVisible((v) => !v),
                  "aria-label": apiKeyVisible ? "Hide API key" : "Show API key",
                  "aria-pressed": apiKeyVisible,
                  children: apiKeyVisible ? /* @__PURE__ */ jsxRuntimeExports.jsx(EyeOffIcon, {}) : /* @__PURE__ */ jsxRuntimeExports.jsx(EyeIcon, {})
                }
              )
            ] })
          ] })
        ] }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$6.actions, children: session ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: styles$6.logoutButton,
              onClick: handleLogout,
              disabled: loggingOut || deletingAccount,
              children: loggingOut ? "Logging out…" : "Log out"
            }
          ),
          onRequestDeleteAccount && /* @__PURE__ */ jsxRuntimeExports.jsx(
            "button",
            {
              type: "button",
              className: styles$6.deleteAccountButton,
              onClick: () => {
                onRequestDeleteAccount();
              },
              disabled: loggingOut || deletingAccount,
              children: "Delete account"
            }
          )
        ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "button",
            className: styles$6.connectButton,
            onClick: onConnect,
            children: "Connect API key"
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("footer", { className: styles$6.legalFooter, children: [
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "a",
            {
              className: styles$6.legalLink,
              href: PRIVACY_POLICY_URL,
              target: "_blank",
              rel: "noopener noreferrer",
              children: "Privacy policy"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$6.legalSep, "aria-hidden": true, children: "·" }),
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "a",
            {
              className: styles$6.legalLink,
              href: SUPPORT_URL,
              target: "_blank",
              rel: "noopener noreferrer",
              children: "Support"
            }
          ),
          /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$6.versionLabel, children: [
            "v",
            APP_VERSION
          ] })
        ] })
      ] })
    ] });
  }
  function EyeIcon() {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "path",
        {
          d: "M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z",
          stroke: "currentColor",
          strokeWidth: "2",
          strokeLinecap: "round",
          strokeLinejoin: "round"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx("circle", { cx: "12", cy: "12", r: "3", stroke: "currentColor", strokeWidth: "2" })
    ] });
  }
  function EyeOffIcon() {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "path",
        {
          d: "M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-10-8-10-8a18.45 18.45 0 0 1 5.06-5.94",
          stroke: "currentColor",
          strokeWidth: "2",
          strokeLinecap: "round",
          strokeLinejoin: "round"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "path",
        {
          d: "M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 10 8 10 8a18.5 18.5 0 0 1-2.16 3.19",
          stroke: "currentColor",
          strokeWidth: "2",
          strokeLinecap: "round",
          strokeLinejoin: "round"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "path",
        {
          d: "M1 1l22 22",
          stroke: "currentColor",
          strokeWidth: "2",
          strokeLinecap: "round",
          strokeLinejoin: "round"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "path",
        {
          d: "M14.12 14.12a3 3 0 0 1-4.24-4.24",
          stroke: "currentColor",
          strokeWidth: "2",
          strokeLinecap: "round",
          strokeLinejoin: "round"
        }
      )
    ] });
  }
  const wrap = "_wrap_1uhwi_1";
  const bell = "_bell_1uhwi_7";
  const bellOpen = "_bellOpen_1uhwi_38";
  const bellUrgent = "_bellUrgent_1uhwi_45";
  const badge = "_badge_1uhwi_51";
  const badgeUrgent = "_badgeUrgent_1uhwi_72";
  const menu = "_menu_1uhwi_76";
  const menuHeader = "_menuHeader_1uhwi_94";
  const menuTitle = "_menuTitle_1uhwi_101";
  const menuMatching = "_menuMatching_1uhwi_107";
  const empty$2 = "_empty_1uhwi_113";
  const list$2 = "_list_1uhwi_125";
  const row$2 = "_row_1uhwi_134";
  const rowLabel = "_rowLabel_1uhwi_143";
  const rowValue = "_rowValue_1uhwi_182";
  const rowValueMatching = "_rowValueMatching_1uhwi_191";
  const volumeRow = "_volumeRow_1uhwi_195";
  const volumeLabel = "_volumeLabel_1uhwi_202";
  const volumeSlider = "_volumeSlider_1uhwi_208";
  const volumeValue = "_volumeValue_1uhwi_222";
  const settingsLink = "_settingsLink_1uhwi_232";
  const styles$5 = {
    wrap,
    bell,
    bellOpen,
    bellUrgent,
    badge,
    badgeUrgent,
    menu,
    menuHeader,
    menuTitle,
    menuMatching,
    empty: empty$2,
    list: list$2,
    row: row$2,
    rowLabel,
    rowValue,
    rowValueMatching,
    volumeRow,
    volumeLabel,
    volumeSlider,
    volumeValue,
    settingsLink
  };
  function AlertsMenu({
    alerts,
    tornXid,
    matchingCount,
    matchingCounts,
    onOpenSettings,
    balance,
    onNavigate
  }) {
    const wrapRef = reactExports.useRef(null);
    const volumeId = reactExports.useId();
    const [open, setOpen] = reactExports.useState(false);
    const [openRowId, setOpenRowId] = reactExports.useState(null);
    const descriptors = reactExports.useMemo(() => {
      const list2 = [
        {
          id: "losses",
          label: "Losses",
          kind: "price",
          value: alerts.alertThreshold,
          onCommit: alerts.onAlertThresholdChange,
          singular: "loss",
          navTarget: { mode: "buying", contractType: "losses" }
        },
        {
          id: "escapes",
          label: "Escapes",
          kind: "price",
          value: alerts.alertEscapeThreshold,
          onCommit: alerts.onAlertEscapeThresholdChange,
          singular: "escape",
          navTarget: { mode: "buying", contractType: "escapes" }
        },
        {
          id: "stalemates",
          label: "Stalemates",
          kind: "price",
          value: alerts.alertStalemateThreshold,
          onCommit: alerts.onAlertStalemateThresholdChange,
          singular: "stalemate",
          navTarget: { mode: "buying", contractType: "stalemates" }
        },
        {
          id: "withdrawals",
          label: "Withdrawals",
          kind: "quantity",
          value: alerts.alertWithdrawalThreshold,
          onCommit: alerts.onAlertWithdrawalThresholdChange,
          navTarget: { mode: "redeeming", serviceType: "withdrawals" }
        },
        {
          id: "bounties",
          label: "Bounties",
          kind: "quantity",
          value: alerts.alertBountyThreshold,
          onCommit: alerts.onAlertBountyThresholdChange,
          navTarget: { mode: "redeeming", serviceType: "bounties" }
        }
      ];
      if (isServiceActionEnabled("embargo")) {
        list2.push({
          id: "embargo",
          label: "Embargo",
          kind: "price",
          value: alerts.alertEmbargoThreshold,
          onCommit: alerts.onAlertEmbargoThresholdChange,
          singular: "embargo",
          navTarget: {
            mode: "redeeming",
            serviceType: "other",
            otherSubtype: "embargo"
          }
        });
      }
      if (isServiceActionEnabled("productivity")) {
        list2.push({
          id: "productivity",
          label: "Productivity",
          kind: "price",
          value: alerts.alertProductivityThreshold,
          onCommit: alerts.onAlertProductivityThresholdChange,
          singular: "boost",
          navTarget: {
            mode: "redeeming",
            serviceType: "other",
            otherSubtype: "productivity-boost"
          }
        });
      }
      if (isServiceActionEnabled("flight-delay")) {
        list2.push({
          id: "flight-delay",
          label: "Flight delay",
          kind: "price",
          value: alerts.alertFlightDelayThreshold,
          onCommit: alerts.onAlertFlightDelayThresholdChange,
          singular: "flight delay",
          navTarget: {
            mode: "redeeming",
            serviceType: "other",
            otherSubtype: "flight-delay"
          }
        });
      }
      for (const kind of SIMPLE_SERVICE_IDS.filter(
        (k) => isServiceActionEnabled(k)
      )) {
        const serviceKind = kind;
        list2.push({
          id: `simple-${serviceKind}`,
          label: SIMPLE_SERVICES[serviceKind].label,
          kind: "price",
          value: alerts.alertSimpleServiceThresholds[serviceKind] ?? null,
          onCommit: (v) => alerts.onAlertSimpleServiceThresholdChange(serviceKind, v),
          singular: SIMPLE_SERVICES[serviceKind].label.toLowerCase(),
          navTarget: {
            mode: "redeeming",
            serviceType: "other",
            otherSubtype: serviceKind
          }
        });
      }
      return list2;
    }, [alerts]);
    const configured = descriptors.filter((d) => d.value !== null);
    const configuredCount = configured.length;
    reactExports.useEffect(() => {
      if (!open) return void 0;
      const handlePointerDown = (event) => {
        const path = event.composedPath();
        if (!path.includes(wrapRef.current)) {
          setOpen(false);
          setOpenRowId(null);
        }
      };
      document.addEventListener("mousedown", handlePointerDown);
      return () => document.removeEventListener("mousedown", handlePointerDown);
    }, [open]);
    const formatValue = (d) => d.value === null ? "" : d.kind === "price" ? formatExtensionPoints(d.value) : d.value.toLocaleString("en-US");
    const badgeCount = matchingCount;
    const badgeUrgent2 = matchingCount > 0;
    const ariaLabel = matchingCount > 0 ? `Alerts: ${matchingCount} matching now` : configuredCount > 0 ? `Alerts: ${configuredCount} set` : "Alerts";
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { ref: wrapRef, className: styles$5.wrap, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "button",
        {
          type: "button",
          className: `${styles$5.bell} ${open ? styles$5.bellOpen : ""} ${badgeUrgent2 ? styles$5.bellUrgent : ""}`,
          onClick: () => {
            setOpen((o) => !o);
            setOpenRowId(null);
          },
          "aria-haspopup": "dialog",
          "aria-expanded": open,
          "aria-label": ariaLabel,
          title: "Alerts",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Bell, { size: 18, strokeWidth: 2, "aria-hidden": true }),
            badgeCount > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(
              "span",
              {
                className: `${styles$5.badge} ${badgeUrgent2 ? styles$5.badgeUrgent : ""}`,
                "aria-hidden": true,
                children: badgeCount > 9 ? "9+" : badgeCount
              }
            )
          ]
        }
      ),
      open && /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          className: styles$5.menu,
          role: "dialog",
          "aria-label": "Your alerts",
          onKeyDown: (e) => {
            if (e.key === "Escape") {
              e.preventDefault();
              setOpen(false);
              setOpenRowId(null);
            }
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$5.menuHeader, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$5.menuTitle, children: "Your alerts" }),
              matchingCount > 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$5.menuMatching, children: [
                matchingCount,
                " matching now"
              ] })
            ] }),
            tornXid === null ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$5.empty, children: "Connect your API key to set alerts and get pinged when a matching listing appears." }) : configuredCount === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: styles$5.empty, children: [
              "No alerts set yet. Tap the",
              " ",
              /* @__PURE__ */ jsxRuntimeExports.jsx(Bell, { size: 12, strokeWidth: 2, "aria-hidden": true }),
              " on the Buy or Sell Services tabs to get pinged the moment a matching listing drops."
            ] }) : /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: styles$5.list, children: configured.map((d) => {
              const count = matchingCounts[d.id] ?? 0;
              const matching = count > 0;
              return /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: styles$5.row, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: styles$5.rowLabel,
                    onClick: () => {
                      setOpen(false);
                      setOpenRowId(null);
                      onNavigate(d.navTarget);
                    },
                    title: `Go to ${d.label}`,
                    children: d.label
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "span",
                  {
                    className: `${styles$5.rowValue} ${matching ? styles$5.rowValueMatching : ""}`,
                    children: formatValue(d)
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  AlertBellPopover,
                  {
                    label: d.label,
                    kind: d.kind,
                    singular: d.singular,
                    value: d.value,
                    onCommit: d.onCommit,
                    balance,
                    open: openRowId === d.id,
                    onOpenChange: (o) => setOpenRowId(o ? d.id : null),
                    matchingCount: count
                  }
                )
              ] }, d.id);
            }) }),
            tornXid !== null && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$5.volumeRow, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("label", { className: styles$5.volumeLabel, htmlFor: volumeId, children: "Sound" }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "input",
                {
                  id: volumeId,
                  className: styles$5.volumeSlider,
                  type: "range",
                  min: 0,
                  max: 100,
                  step: 1,
                  value: alerts.alertVolume,
                  "aria-label": "Alert sound volume",
                  onChange: (e) => alerts.onAlertVolumeChange(Number(e.target.value))
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$5.volumeValue, children: [
                alerts.alertVolume,
                "%"
              ] })
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "button",
              {
                type: "button",
                className: styles$5.settingsLink,
                onClick: () => {
                  setOpen(false);
                  setOpenRowId(null);
                  onOpenSettings();
                },
                children: "Open all alert settings"
              }
            )
          ]
        }
      )
    ] });
  }
  const backdrop = "_backdrop_1yz7u_1";
  const backdropVisible = "_backdropVisible_1yz7u_15";
  const panel = "_panel_1yz7u_20";
  const panelOpen = "_panelOpen_1yz7u_41";
  const header = "_header_1yz7u_45";
  const headerRow = "_headerRow_1yz7u_54";
  const title$1 = "_title_1yz7u_61";
  const headerActions = "_headerActions_1yz7u_72";
  const settingsButton = "_settingsButton_1yz7u_80";
  const settingsButtonActive = "_settingsButtonActive_1yz7u_105";
  const balanceButton = "_balanceButton_1yz7u_117";
  const body = "_body_1yz7u_149";
  const bodyScrollPanel = "_bodyScrollPanel_1yz7u_157";
  const bodyPanelLockOverlay = "_bodyPanelLockOverlay_1yz7u_167";
  const bodyPanelLocked = "_bodyPanelLocked_1yz7u_174";
  const bodyPanelLockMessage = "_bodyPanelLockMessage_1yz7u_194";
  const boardLoading = "_boardLoading_1yz7u_203";
  const styles$4 = {
    backdrop,
    backdropVisible,
    panel,
    panelOpen,
    header,
    headerRow,
    title: title$1,
    headerActions,
    settingsButton,
    settingsButtonActive,
    balanceButton,
    body,
    bodyScrollPanel,
    bodyPanelLockOverlay,
    bodyPanelLocked,
    bodyPanelLockMessage,
    boardLoading
  };
  function Sidebar({
    open,
    allowClose = true,
    mode,
    onModeChange,
    onClose,
    balance,
    onListingSelect,
    onCancelOwnListing,
    showLossContractPanel,
    showLossCompletedPanel,
    displayLossContract,
    completedLossContract,
    contractSecondsRemaining,
    onDismissCompletedLoss,
    contractActive,
    marketListings,
    buyerOrders,
    hasActiveFulfillment,
    highlightedListingId,
    ownListingIds,
    onBuyerSubmit,
    onCancelBuyerOrder,
    onShowInProgressView,
    onShowBuyerOrderProgress,
    onDismissCompletedBuyerOrder,
    buyerFormResetKey,
    onBalanceClick,
    onAddBalance,
    redeemingListings,
    ownRedeemingListingIds,
    myRedeemingRequest,
    onRedeemingListingSelect,
    onCancelRedeemingRequest,
    onCancelMyRedeemingRequest,
    showRedeemContractPanel,
    showRedeemCompletedPanel,
    displayRedeemFulfillment,
    completedRedeemFulfillment,
    onDismissCompletedRedeem,
    completedService,
    onDismissCompletedService,
    redeemingContractActive,
    redeemingSecondsRemaining,
    highlightedRedeemingListingId,
    settingsOpen,
    onSettingsToggle,
    onOpenSettings,
    alerts,
    modeAlertHighlights,
    contractTypeAlertHighlights,
    withdrawalAlertActive,
    bountyAlertActive,
    embargoAlertActive,
    productivityAlertActive,
    flightDelayAlertActive,
    simpleServiceAlertActive,
    onNavigateToAlert,
    panelNav,
    matchingAlertCount,
    matchingAlertCounts,
    alertingOtherSubtypes,
    session,
    onLogout,
    onRequestDeleteAccount,
    onConnectApiKey,
    onOpenReferrals,
    onViewArchive,
    archiveCount,
    deletingAccount = false,
    currentUserXid,
    balanceLoading = false,
    boardLoading: boardLoading2 = false,
    sessionLoading = false,
    suppressBalanceConfetti = false,
    onTurnInLossContract,
    lossTurnInState,
    lossTurnInError,
    onTurnInRedeemFulfillment,
    redeemTurnInState,
    redeemTurnInError,
    payoutConversion,
    activeInsurancePolicies,
    onInsuranceExpired,
    onOpenInsuranceModal,
    onFileInsuranceClaim,
    onDisableInsuranceAutoRenew,
    activeBountyOrders,
    onOpenBountiesModal,
    onCancelBountyOrder,
    onOpenWithdraw,
    onOpenProductivityBoost,
    activeProductivityBoosts,
    onCancelProductivityBoost,
    onBountyOrderSelect,
    showBountyContractPanel,
    displayBountyFulfillment,
    bountySecondsRemaining,
    bountyContractActive,
    serviceContractActive,
    onTurnInBountyFulfillment,
    bountyTurnInState,
    bountyTurnInError,
    onTakeProductivityBoost,
    showProductivityBoostContractPanel,
    activeProductivityBoostFulfillment,
    productivityBoostSecondsRemaining,
    onTurnInProductivityBoost,
    productivityBoostTurnInState,
    productivityBoostTurnInError,
    onOpenEmbargo,
    activeEmbargos,
    embargoListings,
    onCancelEmbargo,
    onTakeEmbargo,
    showEmbargoContractPanel,
    activeEmbargoFulfillment,
    embargoSecondsRemaining,
    onTurnInEmbargo,
    embargoTurnInState,
    embargoTurnInError,
    activeReferences,
    referencesListings,
    onCancelReferences,
    onTakeReferences,
    showReferencesContractPanel,
    activeReferencesFulfillment,
    referencesSecondsRemaining,
    onTurnInReferences,
    referencesTurnInState,
    referencesTurnInError,
    onViewReferencesReport,
    activeBountyReveals,
    bountyRevealListings,
    onCancelBountyReveal,
    onTakeBountyReveal,
    showBountyRevealContractPanel,
    activeBountyRevealFulfillment,
    bountyRevealSecondsRemaining,
    onTurnInBountyReveal,
    bountyRevealTurnInState,
    bountyRevealTurnInError,
    onViewBountyRevealReport,
    onOpenFlightDelay,
    activeFlightDelays,
    onCancelFlightDelay,
    onTakeFlightDelay,
    showFlightDelayContractPanel,
    activeFlightDelayFulfillment,
    flightDelaySecondsRemaining,
    onTurnInFlightDelay,
    flightDelayTurnInState,
    flightDelayTurnInError,
    onOpenSimpleService,
    activeSimpleServices,
    onCancelSimpleService,
    onTakeSimpleService,
    showSimpleServiceContractPanel,
    activeSimpleServiceFulfillment,
    simpleServiceSecondsRemaining,
    onTurnInSimpleService,
    simpleServiceTurnInState,
    simpleServiceTurnInError,
    firstContractCompleted
  }) {
    const {
      alertThreshold,
      alertEscapeThreshold,
      alertStalemateThreshold,
      alertWithdrawalThreshold,
      alertBountyThreshold,
      alertEmbargoThreshold,
      alertProductivityThreshold,
      alertFlightDelayThreshold,
      alertSimpleServiceThresholds,
      onAlertThresholdChange,
      onAlertEscapeThresholdChange,
      onAlertStalemateThresholdChange,
      onAlertWithdrawalThresholdChange,
      onAlertBountyThresholdChange,
      onAlertEmbargoThresholdChange,
      onAlertProductivityThresholdChange,
      onAlertFlightDelayThresholdChange,
      onAlertSimpleServiceThresholdChange
    } = alerts;
    const balanceButtonRef = reactExports.useRef(null);
    const sellTabRef = reactExports.useRef(null);
    const buyTabRef = reactExports.useRef(null);
    const takeContractRef = reactExports.useRef(null);
    const insuranceTour = useInsuranceAdTourContext();
    const buyTabSpotlightVisible = insuranceTour.phase === "buyTab";
    const buyTabSpotlightOpacity = useSpotlightFade(buyTabSpotlightVisible);
    const bountyTour = useBountyAdTourContext();
    const bountyBuyTabSpotlightVisible = bountyTour.phase === "buyTab";
    const bountyBuyTabSpotlightOpacity = useSpotlightFade(
      bountyBuyTabSpotlightVisible
    );
    const ownBountyOrderIds = reactExports.useMemo(
      () => new Set(
        activeBountyOrders.filter((o) => o.buyerId === currentUserXid).map((o) => o.id)
      ),
      [activeBountyOrders, currentUserXid]
    );
    const myBountyOrders = reactExports.useMemo(
      () => activeBountyOrders.filter((o) => o.buyerId === currentUserXid),
      [activeBountyOrders, currentUserXid]
    );
    const extensionMount = getExtensionShadowMount();
    const topLossTarget = reactExports.useMemo(
      () => findTopSelectableLossListing(
        marketListings,
        ownListingIds,
        currentUserXid
      ),
      [marketListings, ownListingIds, currentUserXid]
    );
    const sellerAudience = getCampaignAudience() === "seller";
    const sellTutorialEnabled = open && !settingsOpen && isTouchPrimaryInput() && !sellerAudience;
    const {
      takeContractPhaseActive,
      showBackdrop: showSellTabTutorial,
      backdropOpacity: sellTabTutorialOpacity,
      fadeMs: sellTabTutorialFadeMs,
      notifySellTabSelected,
      notifyTakeContractSelected,
      onBackdropTransitionEnd: onSellTabTutorialTransitionEnd,
      sellTabTutorialBlocking,
      takeContractTutorialBlocking
    } = useSellTabTutorial({
      enabled: sellTutorialEnabled,
      mode,
      boardLoading: boardLoading2,
      takeContractTargetId: (topLossTarget == null ? void 0 : topLossTarget.id) ?? null
    });
    const sellAttacksTutorialEnabled = open && !settingsOpen && !isTouchPrimaryInput() && !sellerAudience;
    const {
      showBackdrop: showSellAttacksTutorial,
      backdropOpacity: sellAttacksTutorialOpacity,
      fadeMs: sellAttacksTutorialFadeMs,
      notifyTakeContractSelected: notifySellAttacksTakeContractSelected,
      onBackdropTransitionEnd: onSellAttacksTutorialTransitionEnd,
      takeContractTutorialActive: sellAttacksTakeContractActive
    } = useSellAttacksTakeContractTutorial({
      enabled: sellAttacksTutorialEnabled,
      mode,
      boardLoading: boardLoading2,
      takeContractTargetId: (topLossTarget == null ? void 0 : topLossTarget.id) ?? null
    });
    const {
      goSellAttacksActive: sellerGoSellAttacksActive,
      takeContractActive: sellerTakeContractActive,
      notifySwitchedToSellAttacks: notifySellerSwitchedToSellAttacks,
      notifyTakeContractSelected: notifySellerTakeContractSelected,
      notifySignedIn: notifySellerSignedIn
    } = useSellerSidebarTour({
      enabled: open && !settingsOpen && sellerAudience,
      mode,
      topLossTargetId: (topLossTarget == null ? void 0 : topLossTarget.id) ?? null
    });
    const sellerGoSellAttacksOpacity = useSpotlightFade(sellerGoSellAttacksActive);
    const sellerTakeContractOpacity = useSpotlightFade(sellerTakeContractActive);
    const wasSignedInRef = reactExports.useRef(session !== null);
    reactExports.useEffect(() => {
      const signedIn = session !== null;
      if (signedIn && !wasSignedInRef.current && sellerAudience) ;
      wasSignedInRef.current = signedIn;
    }, [session, sellerAudience, notifySellerSignedIn]);
    const withdrawingTutorialEnabled = open && !settingsOpen && firstContractCompleted;
    const {
      showBackdrop: showWithdrawingTutorial,
      backdropOpacity: withdrawingTutorialOpacity,
      fadeMs: withdrawingTutorialFadeMs,
      dismissTutorial: dismissWithdrawingTutorial,
      onBackdropTransitionEnd: onWithdrawingTutorialTransitionEnd,
      tutorialBlocking: withdrawingTutorialBlocking
    } = useWithdrawingBalanceTutorial(withdrawingTutorialEnabled);
    const handleBalanceClick = reactExports.useCallback(() => {
      if (withdrawingTutorialBlocking) {
        dismissWithdrawingTutorial();
      }
      onBalanceClick();
    }, [
      withdrawingTutorialBlocking,
      dismissWithdrawingTutorial,
      onBalanceClick
    ]);
    const handleModeChange = reactExports.useCallback(
      (next) => {
        if (sellTabTutorialBlocking && next === "buying") {
          notifySellTabSelected();
        }
        if (next === "buying") {
          notifySellerSwitchedToSellAttacks();
        }
        onModeChange(next);
      },
      [
        sellTabTutorialBlocking,
        notifySellTabSelected,
        notifySellerSwitchedToSellAttacks,
        onModeChange
      ]
    );
    const handleListingSelect = reactExports.useCallback(
      (listing) => {
        if (listing.id === (topLossTarget == null ? void 0 : topLossTarget.id)) {
          if (takeContractTutorialBlocking) notifyTakeContractSelected();
          if (sellAttacksTakeContractActive) {
            notifySellAttacksTakeContractSelected();
          }
          if (sellerTakeContractActive) {
            notifySellerTakeContractSelected();
          }
        }
        onListingSelect(listing);
      },
      [
        takeContractTutorialBlocking,
        sellAttacksTakeContractActive,
        sellerTakeContractActive,
        topLossTarget == null ? void 0 : topLossTarget.id,
        notifyTakeContractSelected,
        notifySellAttacksTakeContractSelected,
        notifySellerTakeContractSelected,
        onListingSelect
      ]
    );
    const panelScrollable = !settingsOpen && (mode === "buying" || mode === "selling" || mode === "redeeming");
    const activeFulfillmentKind = getActiveFulfillmentKind(
      contractActive,
      redeemingContractActive,
      bountyContractActive,
      serviceContractActive
    );
    const panelLocked = !settingsOpen && isPanelLockedByActiveFulfillment(mode, activeFulfillmentKind);
    const panelLockMessage = getPanelLockMessage(mode, activeFulfillmentKind);
    const modeSwitchValue = settingsOpen ? null : mode;
    const panelVisible = allowClose ? open : true;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PanelButtonTutorial,
        {
          visible: showWithdrawingTutorial,
          opacity: withdrawingTutorialOpacity,
          fadeMs: withdrawingTutorialFadeMs,
          targetRef: balanceButtonRef,
          onTransitionEnd: onWithdrawingTutorialTransitionEnd,
          portalTarget: extensionMount,
          layerZIndex: EXTENSION_SPOTLIGHT_Z,
          onDarknessClick: handleBalanceClick
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PanelButtonTutorial,
        {
          visible: showSellTabTutorial,
          opacity: sellTabTutorialOpacity,
          fadeMs: sellTabTutorialFadeMs,
          targetRef: takeContractPhaseActive ? takeContractRef : sellTabRef,
          onTransitionEnd: onSellTabTutorialTransitionEnd,
          portalTarget: extensionMount,
          layerZIndex: EXTENSION_SPOTLIGHT_Z,
          layoutKey: `${mode}:${boardLoading2}:${(topLossTarget == null ? void 0 : topLossTarget.id) ?? ""}`
        },
        takeContractPhaseActive ? "take-contract" : "sell-tab"
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PanelButtonTutorial,
        {
          visible: buyTabSpotlightVisible,
          opacity: buyTabSpotlightOpacity,
          fadeMs: 300,
          targetRef: buyTabRef,
          onTransitionEnd: () => {
          },
          portalTarget: extensionMount,
          layerZIndex: EXTENSION_SPOTLIGHT_Z,
          layoutKey: modeSwitchValue
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PanelButtonTutorial,
        {
          visible: bountyBuyTabSpotlightVisible,
          opacity: bountyBuyTabSpotlightOpacity,
          fadeMs: 300,
          targetRef: buyTabRef,
          onTransitionEnd: () => {
          },
          portalTarget: extensionMount,
          layerZIndex: EXTENSION_SPOTLIGHT_Z,
          layoutKey: modeSwitchValue,
          caption: "Open the Buy tab to place bulk bounties through The Panel."
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PanelButtonTutorial,
        {
          visible: showSellAttacksTutorial,
          opacity: sellAttacksTutorialOpacity,
          fadeMs: sellAttacksTutorialFadeMs,
          targetRef: takeContractRef,
          onTransitionEnd: onSellAttacksTutorialTransitionEnd,
          portalTarget: extensionMount,
          layerZIndex: EXTENSION_SPOTLIGHT_Z,
          layoutKey: `${mode}:${boardLoading2}:${(topLossTarget == null ? void 0 : topLossTarget.id) ?? ""}`
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PanelButtonTutorial,
        {
          visible: sellerGoSellAttacksActive,
          opacity: sellerGoSellAttacksOpacity,
          fadeMs: 300,
          targetRef: sellTabRef,
          onTransitionEnd: () => {
          },
          portalTarget: extensionMount,
          layerZIndex: EXTENSION_SPOTLIGHT_Z,
          layoutKey: modeSwitchValue
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PanelButtonTutorial,
        {
          visible: sellerTakeContractActive,
          opacity: sellerTakeContractOpacity,
          fadeMs: 300,
          targetRef: takeContractRef,
          onTransitionEnd: () => {
          },
          portalTarget: extensionMount,
          layerZIndex: EXTENSION_SPOTLIGHT_Z,
          layoutKey: `${mode}:${boardLoading2}:${(topLossTarget == null ? void 0 : topLossTarget.id) ?? ""}`
        }
      ),
      allowClose ? /* @__PURE__ */ jsxRuntimeExports.jsx(
        "button",
        {
          type: "button",
          className: `${styles$4.backdrop} ${open ? styles$4.backdropVisible : ""}`,
          "aria-label": "Close marketplace sidebar",
          tabIndex: open ? 0 : -1,
          onClick: onClose
        }
      ) : null,
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "aside",
        {
          className: `${styles$4.panel} ${panelVisible ? styles$4.panelOpen : ""}`,
          "aria-hidden": !panelVisible,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs("header", { className: styles$4.header, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$4.headerRow, children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h1", { className: styles$4.title, children: BRAND_NAME }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$4.headerActions, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    BalanceButton,
                    {
                      ref: balanceButtonRef,
                      balance,
                      panelOpen: panelVisible,
                      tornXid: (session == null ? void 0 : session.torn_xid) ?? null,
                      balanceLoading,
                      suppressConfetti: suppressBalanceConfetti,
                      onClick: handleBalanceClick,
                      className: styles$4.balanceButton
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    AlertsMenu,
                    {
                      alerts,
                      tornXid: (session == null ? void 0 : session.torn_xid) ?? null,
                      matchingCount: matchingAlertCount,
                      matchingCounts: matchingAlertCounts,
                      onOpenSettings,
                      balance,
                      onNavigate: onNavigateToAlert
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      type: "button",
                      className: `${styles$4.settingsButton} ${settingsOpen ? styles$4.settingsButtonActive : ""}`,
                      onClick: onSettingsToggle,
                      "aria-label": "Settings",
                      "aria-pressed": settingsOpen,
                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(SettingsIcon, {})
                    }
                  )
                ] })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                ModeSwitch,
                {
                  mode: modeSwitchValue,
                  onModeChange: handleModeChange,
                  alertHighlightedModes: modeAlertHighlights,
                  sellTabRef,
                  buyTabRef
                }
              )
            ] }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "div",
              {
                className: `${styles$4.body} ${panelScrollable ? styles$4.bodyScrollPanel : ""} ${panelLocked ? styles$4.bodyPanelLocked : ""}`,
                role: settingsOpen ? "region" : "tabpanel",
                id: settingsOpen ? "tlm-panel-settings" : `tlm-panel-${mode}`,
                "aria-labelledby": settingsOpen ? void 0 : `tlm-tab-${mode}`,
                children: [
                  panelLocked && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$4.bodyPanelLockOverlay, role: "status", children: /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$4.bodyPanelLockMessage, children: panelLockMessage }) }),
                  boardLoading2 && panelScrollable ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$4.boardLoading, role: "status", children: "Loading listings…" }) : settingsOpen ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                    SettingsPanel,
                    {
                      session,
                      tornXid: (session == null ? void 0 : session.torn_xid) ?? null,
                      alerts,
                      onLogout,
                      onRequestDeleteAccount,
                      onConnect: onConnectApiKey,
                      deletingAccount: onRequestDeleteAccount ? deletingAccount : void 0,
                      onOpenReferrals,
                      onViewArchive,
                      archiveCount,
                      balance
                    }
                  ) : mode === "buying" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                    BuyingPanel,
                    {
                      navRequest: panelNav && panelNav.target.mode === "buying" ? {
                        token: panelNav.token,
                        contractType: panelNav.target.contractType
                      } : void 0,
                      balance,
                      listings: marketListings,
                      onListingSelect: handleListingSelect,
                      onCancelOwnListing,
                      showLossContractPanel,
                      showLossCompletedPanel,
                      displayLossContract,
                      completedLossContract,
                      contractSecondsRemaining,
                      onDismissCompletedLoss,
                      highlightedListingId,
                      ownListingIds,
                      currentUserXid,
                      onTurnInContract: onTurnInLossContract,
                      lossTurnInState,
                      lossTurnInError,
                      payoutConversion,
                      tornXid: (session == null ? void 0 : session.torn_xid) ?? null,
                      sessionLoading,
                      contractTypeAlertHighlights,
                      alertThreshold,
                      alertEscapeThreshold,
                      alertStalemateThreshold,
                      onAlertThresholdChange,
                      onAlertEscapeThresholdChange,
                      onAlertStalemateThresholdChange,
                      onOpenSettings,
                      takeContractTutorialTargetId: takeContractTutorialBlocking || sellAttacksTakeContractActive || sellerTakeContractActive ? (topLossTarget == null ? void 0 : topLossTarget.id) ?? null : null,
                      takeContractTutorialRef: takeContractRef
                    }
                  ) : mode === "selling" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                    BuyersPanel,
                    {
                      buyerOrders,
                      balance,
                      hasActiveFulfillment,
                      onSubmitOrder: onBuyerSubmit,
                      onCancelBuyerOrder,
                      onShowInProgressView,
                      onShowBuyerOrderProgress,
                      onDismissCompletedBuyerOrder,
                      myRedeemingRequest,
                      onCancelMyRedeemingRequest,
                      formResetKey: buyerFormResetKey,
                      onAddBalance,
                      payoutConversion,
                      tornXid: (session == null ? void 0 : session.torn_xid) ?? null,
                      activeInsurancePolicies,
                      onInsuranceExpired,
                      onOpenInsuranceModal,
                      onFileInsuranceClaim,
                      onDisableInsuranceAutoRenew,
                      activeBountyOrders: myBountyOrders,
                      onOpenBountiesModal,
                      onCancelBountyOrder,
                      onOpenWithdraw,
                      onOpenProductivityBoost,
                      activeProductivityBoosts,
                      onCancelProductivityBoost,
                      onOpenEmbargo,
                      activeEmbargos,
                      onCancelEmbargo,
                      activeReferences,
                      onCancelReferences,
                      onViewReferencesReport,
                      activeBountyReveals,
                      onCancelBountyReveal,
                      onViewBountyRevealReport,
                      onOpenFlightDelay,
                      activeFlightDelays,
                      onCancelFlightDelay,
                      onOpenSimpleService,
                      activeSimpleServices,
                      onCancelSimpleService
                    }
                  ) : /* @__PURE__ */ jsxRuntimeExports.jsx(
                    RedeemingPanel,
                    {
                      navRequest: panelNav && panelNav.target.mode === "redeeming" ? {
                        token: panelNav.token,
                        serviceType: panelNav.target.serviceType,
                        otherSubtype: panelNav.target.otherSubtype
                      } : void 0,
                      balance,
                      listings: redeemingListings,
                      ownListingIds: ownRedeemingListingIds,
                      onListingSelect: onRedeemingListingSelect,
                      onCancelRequest: onCancelRedeemingRequest,
                      showRedeemContractPanel,
                      showRedeemCompletedPanel,
                      displayRedeemFulfillment,
                      completedRedeemFulfillment,
                      redeemingSecondsRemaining,
                      onDismissCompletedRedeem,
                      completedService,
                      onDismissCompletedService,
                      highlightedListingId: highlightedRedeemingListingId,
                      onTurnInFulfillment: onTurnInRedeemFulfillment,
                      redeemTurnInState,
                      redeemTurnInError,
                      payoutConversion,
                      onOpenSettings,
                      tornXid: (session == null ? void 0 : session.torn_xid) ?? null,
                      sessionLoading,
                      withdrawalAlertActive,
                      bountyAlertActive,
                      embargoAlertActive,
                      productivityAlertActive,
                      flightDelayAlertActive,
                      simpleServiceAlertActive,
                      alertingOtherSubtypes,
                      alertWithdrawalThreshold,
                      alertBountyThreshold,
                      alertEmbargoThreshold,
                      alertProductivityThreshold,
                      alertFlightDelayThreshold,
                      alertSimpleServiceThresholds,
                      onAlertWithdrawalThresholdChange,
                      onAlertBountyThresholdChange,
                      onAlertEmbargoThresholdChange,
                      onAlertProductivityThresholdChange,
                      onAlertFlightDelayThresholdChange,
                      onAlertSimpleServiceThresholdChange,
                      bountyOrders: activeBountyOrders,
                      ownBountyOrderIds,
                      onBountyOrderSelect,
                      onCancelBountyOrder,
                      showBountyContractPanel,
                      displayBountyFulfillment,
                      bountySecondsRemaining,
                      onTurnInBountyFulfillment,
                      bountyTurnInState,
                      bountyTurnInError,
                      productivityBoostListings: activeProductivityBoosts,
                      onCancelProductivityBoost,
                      onTakeProductivityBoost,
                      showProductivityBoostContractPanel,
                      activeProductivityBoostFulfillment,
                      productivityBoostSecondsRemaining,
                      onTurnInProductivityBoost,
                      productivityBoostTurnInState,
                      productivityBoostTurnInError,
                      embargoListings,
                      onCancelEmbargo,
                      onTakeEmbargo,
                      showEmbargoContractPanel,
                      activeEmbargoFulfillment,
                      embargoSecondsRemaining,
                      onTurnInEmbargo,
                      embargoTurnInState,
                      embargoTurnInError,
                      referencesListings,
                      onCancelReferences,
                      onTakeReferences,
                      showReferencesContractPanel,
                      activeReferencesFulfillment,
                      referencesSecondsRemaining,
                      onTurnInReferences,
                      referencesTurnInState,
                      referencesTurnInError,
                      bountyRevealListings,
                      onCancelBountyReveal,
                      onTakeBountyReveal,
                      showBountyRevealContractPanel,
                      activeBountyRevealFulfillment,
                      bountyRevealSecondsRemaining,
                      onTurnInBountyReveal,
                      bountyRevealTurnInState,
                      bountyRevealTurnInError,
                      flightDelayListings: activeFlightDelays,
                      onCancelFlightDelay,
                      onTakeFlightDelay,
                      showFlightDelayContractPanel,
                      activeFlightDelayFulfillment,
                      flightDelaySecondsRemaining,
                      onTurnInFlightDelay,
                      flightDelayTurnInState,
                      flightDelayTurnInError,
                      simpleServiceListings: activeSimpleServices,
                      onCancelSimpleService,
                      onTakeSimpleService,
                      showSimpleServiceContractPanel,
                      activeSimpleServiceFulfillment,
                      simpleServiceSecondsRemaining,
                      onTurnInSimpleService,
                      simpleServiceTurnInState,
                      simpleServiceTurnInError
                    }
                  )
                ]
              }
            )
          ]
        }
      )
    ] });
  }
  function SettingsIcon() {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "path",
        {
          d: "M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z",
          stroke: "currentColor",
          strokeWidth: "2",
          strokeLinecap: "round",
          strokeLinejoin: "round"
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "path",
        {
          d: "M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z",
          stroke: "currentColor",
          strokeWidth: "2",
          strokeLinecap: "round",
          strokeLinejoin: "round"
        }
      )
    ] });
  }
  const TORN_DRUG_LOG_PERMISSION_ERROR_CODE = "torn_drug_log_permission";
  const TORN_DRUG_LOG_PERMISSION_MESSAGE = "Your Torn API key needs drug log access (log category 61). Log out, then reconnect with a new key from Create API Key.";
  class TornDrugLogPermissionError extends Error {
    constructor(message = TORN_DRUG_LOG_PERMISSION_MESSAGE) {
      super(message);
      __publicField(this, "code", TORN_DRUG_LOG_PERMISSION_ERROR_CODE);
      this.name = "TornDrugLogPermissionError";
    }
  }
  function isTornDrugLogPermissionError(error2) {
    return error2 instanceof TornDrugLogPermissionError || typeof error2 === "object" && error2 !== null && "code" in error2 && error2.code === TORN_DRUG_LOG_PERMISSION_ERROR_CODE;
  }
  const STORAGE_KEY$1 = "api_key_create_button_intro_seen";
  async function hasSeenApiKeyCreateButtonTutorial() {
    try {
      return await getPlatformRuntime().storage.get(STORAGE_KEY$1) === true;
    } catch {
      return false;
    }
  }
  async function markApiKeyCreateButtonTutorialSeen() {
    try {
      await getPlatformRuntime().storage.set(STORAGE_KEY$1, true);
    } catch {
    }
  }
  const STORAGE_KEY = "api_key_create_button_clicked";
  async function hasClickedApiKeyCreateButton() {
    try {
      return await getPlatformRuntime().storage.get(STORAGE_KEY) === true;
    } catch {
      return false;
    }
  }
  async function markApiKeyCreateButtonClicked() {
    try {
      await getPlatformRuntime().storage.set(STORAGE_KEY, true);
    } catch {
    }
  }
  async function clearApiKeyCreateButtonClicked() {
    try {
      await getPlatformRuntime().storage.set(STORAGE_KEY, false);
    } catch {
    }
  }
  const overlay = "_overlay_o0lju_1";
  const overlaySpotlightActive = "_overlaySpotlightActive_o0lju_12";
  const card = "_card_o0lju_16";
  const closeButton = "_closeButton_o0lju_29";
  const title = "_title_o0lju_64";
  const text = "_text_o0lju_70";
  const tooltipWrap = "_tooltipWrap_o0lju_77";
  const tooltipTrigger = "_tooltipTrigger_o0lju_85";
  const tooltip = "_tooltip_o0lju_77";
  const label = "_label_o0lju_138";
  const input = "_input_o0lju_146";
  const inputPulse = "_inputPulse_o0lju_174";
  const buttonPulse = "_buttonPulse_o0lju_192";
  const actions = "_actions_o0lju_196";
  const secondaryButton = "_secondaryButton_o0lju_202";
  const button = "_button_o0lju_192";
  const error = "_error_o0lju_239";
  const featureError = "_featureError_o0lju_245";
  const privacyLink = "_privacyLink_o0lju_256";
  const tosSection = "_tosSection_o0lju_272";
  const tosToggle = "_tosToggle_o0lju_278";
  const tosChevron = "_tosChevron_o0lju_297";
  const tosTableWrap = "_tosTableWrap_o0lju_307";
  const tosTable = "_tosTable_o0lju_307";
  const styles$3 = {
    overlay,
    overlaySpotlightActive,
    card,
    closeButton,
    title,
    text,
    tooltipWrap,
    tooltipTrigger,
    tooltip,
    label,
    input,
    inputPulse,
    buttonPulse,
    actions,
    secondaryButton,
    button,
    error,
    featureError,
    privacyLink,
    tosSection,
    tosToggle,
    tosChevron,
    tosTableWrap,
    tosTable
  };
  const TORN_API_RULES_URL = "https://www.torn.com/rules.php";
  const TORN_API_KEY_LENGTH = 16;
  const TOOLTIP_QUOTE = "releasing software with malicious or undisclosed functionality is strictly forbidden";
  function ApiKeySetup({ onSubmit, onClose, error: error2 }) {
    const [apiKey, setApiKey] = reactExports.useState("");
    const [submitting, setSubmitting] = reactExports.useState(false);
    const [localError, setLocalError] = reactExports.useState(null);
    const [tosOpen, setTosOpen] = reactExports.useState(false);
    const [spotlightOpacity, setSpotlightOpacity] = reactExports.useState(0);
    const [firstOpenSpotlight, setFirstOpenSpotlight] = reactExports.useState(false);
    const [createKeyClicked, setCreateKeyClicked] = reactExports.useState(
      null
    );
    const [pulseInput, setPulseInput] = reactExports.useState(false);
    const pulseTimeoutRef = reactExports.useRef(null);
    const createApiKeyRef = reactExports.useRef(null);
    const inputRef = reactExports.useRef(null);
    const connectRef = reactExports.useRef(null);
    const displayError = localError ?? error2;
    const showFeatureError = Boolean(
      displayError && (isTornLogPermissionMessage(displayError) || isTornLogPermissionError(displayError) || isTornPerksPermissionError(displayError) || isTornDrugLogPermissionError(displayError) || /perks|drug log|category 61/i.test(displayError))
    );
    const errorText = (() => {
      if (!displayError) return displayError;
      if (isTornPerksPermissionError(displayError) || /perks/i.test(displayError)) {
        return TORN_PERKS_PERMISSION_MESSAGE;
      }
      if (isTornDrugLogPermissionError(displayError) || /drug log|category 61/i.test(displayError)) {
        return TORN_DRUG_LOG_PERMISSION_MESSAGE;
      }
      if (showFeatureError) return TORN_LOG_PERMISSION_MESSAGE;
      return displayError;
    })();
    const showInputSpotlight = pulseInput;
    const showCreateKeySpotlight = (Boolean(displayError) || firstOpenSpotlight && createKeyClicked === false) && !showInputSpotlight;
    const connectReady = !submitting && apiKey.trim().length === TORN_API_KEY_LENGTH;
    const showConnectSpotlight = connectReady && !showCreateKeySpotlight && !showInputSpotlight;
    const inputSpotlightOpacity = useSpotlightFade(showInputSpotlight);
    const connectSpotlightOpacity = useSpotlightFade(showConnectSpotlight);
    reactExports.useEffect(() => {
      let cancelled = false;
      void hasSeenApiKeyCreateButtonTutorial().then((seen) => {
        if (cancelled || seen) return;
        setFirstOpenSpotlight(true);
        void markApiKeyCreateButtonTutorialSeen();
      });
      void hasClickedApiKeyCreateButton().then((clicked) => {
        if (cancelled) return;
        setCreateKeyClicked(clicked);
      });
      return () => {
        cancelled = true;
      };
    }, []);
    reactExports.useEffect(() => {
      if (!showCreateKeySpotlight) {
        setSpotlightOpacity(0);
        return;
      }
      const id2 = requestAnimationFrame(() => {
        requestAnimationFrame(() => setSpotlightOpacity(1));
      });
      return () => cancelAnimationFrame(id2);
    }, [showCreateKeySpotlight]);
    const dismissFirstOpenSpotlight = () => {
      if (firstOpenSpotlight) setFirstOpenSpotlight(false);
    };
    const clearPulseTimer = () => {
      if (pulseTimeoutRef.current !== null) {
        clearTimeout(pulseTimeoutRef.current);
        pulseTimeoutRef.current = null;
      }
    };
    const stopPulse = () => {
      clearPulseTimer();
      if (pulseInput) setPulseInput(false);
    };
    reactExports.useEffect(() => clearPulseTimer, []);
    const submitKey = async (trimmed) => {
      if (submitting) return;
      if (!trimmed) {
        setLocalError("Enter your Torn API key.");
        return;
      }
      setSubmitting(true);
      setLocalError(null);
      try {
        await onSubmit(trimmed);
        void clearApiKeyCreateButtonClicked();
      } catch (err) {
        if (isTornPerksPermissionError(err)) {
          setLocalError(TORN_PERKS_PERMISSION_MESSAGE);
        } else if (isTornDrugLogPermissionError(err)) {
          setLocalError(TORN_DRUG_LOG_PERMISSION_MESSAGE);
        } else if (isTornLogPermissionError(err)) {
          setLocalError(TORN_LOG_PERMISSION_MESSAGE);
        } else {
          setLocalError(err instanceof Error ? err.message : "Sign-in failed");
        }
      } finally {
        setSubmitting(false);
      }
    };
    const handleSubmit = async (e) => {
      e.preventDefault();
      await submitKey(apiKey.trim());
    };
    const openCreateApiKey = () => {
      dismissFirstOpenSpotlight();
      setCreateKeyClicked(true);
      void markApiKeyCreateButtonClicked();
      clearPulseTimer();
      pulseTimeoutRef.current = setTimeout(() => {
        pulseTimeoutRef.current = null;
        setPulseInput(true);
      }, 2e3);
      window.open(CREATE_API_KEY_URL, "_blank", "noopener,noreferrer");
    };
    const openApiRules = () => {
      window.open(TORN_API_RULES_URL, "_blank", "noopener,noreferrer");
    };
    const spotlightLayoutKey = `${displayError ?? ""}:${tosOpen}`;
    const extensionMount = getExtensionShadowMount();
    const createKeyWarning = /* @__PURE__ */ jsxRuntimeExports.jsxs(
      "span",
      {
        style: {
          display: "block",
          color: "#ff4d4f",
          fontWeight: 700,
          fontSize: 13,
          lineHeight: 1.35,
          letterSpacing: 0.2,
          textShadow: "0 1px 2px rgba(0, 0, 0, 0.6)"
        },
        children: [
          "DO NOT SHARE YOUR API KEY WITH OTHER PLAYERS",
          /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}),
          "PASTE YOUR API KEY INTO THE PANEL ONLY"
        ]
      }
    );
    return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PanelButtonTutorial,
        {
          visible: showCreateKeySpotlight,
          opacity: spotlightOpacity,
          fadeMs: 300,
          targetRef: createApiKeyRef,
          layoutKey: spotlightLayoutKey,
          onTransitionEnd: () => {
          },
          portalTarget: extensionMount,
          layerZIndex: API_KEY_SPOTLIGHT_Z,
          caption: createKeyWarning,
          captionWidth: 380
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PanelButtonTutorial,
        {
          visible: showInputSpotlight,
          opacity: inputSpotlightOpacity,
          fadeMs: 300,
          targetRef: inputRef,
          layoutKey: spotlightLayoutKey,
          onTransitionEnd: () => {
          },
          portalTarget: extensionMount,
          layerZIndex: API_KEY_SPOTLIGHT_Z,
          onDarknessClick: stopPulse
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        PanelButtonTutorial,
        {
          visible: showConnectSpotlight,
          opacity: connectSpotlightOpacity,
          fadeMs: 300,
          targetRef: connectRef,
          layoutKey: spotlightLayoutKey,
          onTransitionEnd: () => {
          },
          portalTarget: extensionMount,
          layerZIndex: API_KEY_SPOTLIGHT_Z
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: `${styles$3.overlay} ${showCreateKeySpotlight || showInputSpotlight || showConnectSpotlight ? styles$3.overlaySpotlightActive : ""}`,
          role: "presentation",
          onMouseDown: (e) => overlayMouseDownDismiss(e, onClose),
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "form",
            {
              className: styles$3.card,
              onSubmit: (e) => void handleSubmit(e),
              onClick: (e) => e.stopPropagation(),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "button",
                  {
                    type: "button",
                    className: styles$3.closeButton,
                    "aria-label": "Close",
                    onClick: onClose,
                    disabled: submitting,
                    children: "×"
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { className: styles$3.title, children: "API key required" }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: styles$3.text, children: [
                  "Your API key is never stored server side and always remains on your device.",
                  " ",
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "a",
                    {
                      className: styles$3.privacyLink,
                      href: PRIVACY_POLICY_URL,
                      target: "_blank",
                      rel: "noopener noreferrer",
                      children: "Privacy policy"
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$3.tooltipWrap, children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        className: styles$3.tooltipTrigger,
                        "aria-label": `Torn API rules: "${TOOLTIP_QUOTE}"`,
                        title: `"${TOOLTIP_QUOTE}"`,
                        onClick: openApiRules,
                        children: "?"
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$3.tooltip, role: "tooltip", children: [
                      "“",
                      TOOLTIP_QUOTE,
                      "”"
                    ] })
                  ] })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("label", { className: styles$3.label, children: [
                  "Torn API key",
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "input",
                    {
                      ref: inputRef,
                      className: `${styles$3.input} ${pulseInput ? styles$3.inputPulse : ""}`,
                      type: "password",
                      autoComplete: "off",
                      value: apiKey,
                      onChange: (e) => {
                        dismissFirstOpenSpotlight();
                        const next = e.target.value;
                        setApiKey(next);
                        const trimmed = next.trim();
                        if (trimmed.length === TORN_API_KEY_LENGTH) {
                          stopPulse();
                          void submitKey(trimmed);
                        }
                      },
                      onFocus: dismissFirstOpenSpotlight,
                      placeholder: 'Paste "Custom" or "Full Access" API Key',
                      disabled: submitting
                    }
                  )
                ] }),
                errorText && /* @__PURE__ */ jsxRuntimeExports.jsx(
                  "p",
                  {
                    className: showFeatureError ? styles$3.featureError : styles$3.error,
                    role: "alert",
                    children: errorText
                  }
                ),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$3.actions, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      ref: createApiKeyRef,
                      className: styles$3.secondaryButton,
                      type: "button",
                      onClick: openCreateApiKey,
                      disabled: submitting,
                      children: "Create API Key"
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "button",
                    {
                      ref: connectRef,
                      className: `${styles$3.button} ${showConnectSpotlight ? styles$3.buttonPulse : ""}`,
                      type: "submit",
                      disabled: submitting,
                      children: submitting ? "Connecting…" : "Connect"
                    }
                  )
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$3.tosSection, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    "button",
                    {
                      type: "button",
                      className: styles$3.tosToggle,
                      "aria-expanded": tosOpen,
                      onClick: () => setTosOpen((open) => !open),
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$3.tosChevron, "data-open": tosOpen, "aria-hidden": true, children: "▾" }),
                        "API key terms"
                      ]
                    }
                  ),
                  tosOpen && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: styles$3.tosTableWrap, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("table", { className: styles$3.tosTable, children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx("thead", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "col", children: "Data Storage" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "col", children: "Data Sharing" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "col", children: "Purpose of Use" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "col", children: "Key Storage & Sharing" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("th", { scope: "col", children: "Key Access Level" })
                    ] }) }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx("tbody", { children: /* @__PURE__ */ jsxRuntimeExports.jsxs("tr", { children: [
                      /* @__PURE__ */ jsxRuntimeExports.jsx("td", { children: "Persistent until sign-out or clear extension data" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("td", { children: "Service owner" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("td", { children: "Public community tools" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("td", { children: "Stored client side / Used only for automation" }),
                      /* @__PURE__ */ jsxRuntimeExports.jsx("td", { children: "Custom - basic, equipment, perks, attacks, log (85, 181, 61)" })
                    ] }) })
                  ] }) })
                ] })
              ]
            }
          )
        }
      )
    ] });
  }
  const list$1 = "_list_1k1dk_1";
  const row$1 = "_row_1k1dk_10";
  const party$1 = "_party_1k1dk_21";
  const partyLabel$1 = "_partyLabel_1k1dk_28";
  const partyLink$1 = "_partyLink_1k1dk_36";
  const quantity = "_quantity_1k1dk_49";
  const quantityLabel = "_quantityLabel_1k1dk_57";
  const quantityValue = "_quantityValue_1k1dk_65";
  const timer = "_timer_1k1dk_72";
  const timerLabel = "_timerLabel_1k1dk_80";
  const timerValue = "_timerValue_1k1dk_88";
  const timerExpired = "_timerExpired_1k1dk_95";
  const empty$1 = "_empty_1k1dk_99";
  const styles$2 = {
    list: list$1,
    row: row$1,
    party: party$1,
    partyLabel: partyLabel$1,
    partyLink: partyLink$1,
    quantity,
    quantityLabel,
    quantityValue,
    timer,
    timerLabel,
    timerValue,
    timerExpired,
    empty: empty$1
  };
  function InProgressContractsModal({
    title: title2,
    subtitle: subtitle2,
    quantityLabel: quantityLabel2,
    parties,
    onClose,
    isPaused,
    onPauseToggle
  }) {
    reactExports.useEffect(() => {
      const handleKeyDown = (e) => {
        if (e.key === "Escape") onClose();
      };
      window.addEventListener("keydown", handleKeyDown);
      return () => window.removeEventListener("keydown", handleKeyDown);
    }, [onClose]);
    const portalTarget = getExtensionShadowMount() ?? document.body;
    return reactDomExports.createPortal(
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          className: contractStyles.overlay,
          role: "presentation",
          onMouseDown: (e) => overlayMouseDownDismiss(e, onClose),
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            "div",
            {
              className: contractStyles.dialog,
              role: "dialog",
              "aria-modal": "true",
              "aria-labelledby": "tlm-in-progress-title",
              onClick: (e) => e.stopPropagation(),
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-in-progress-title", className: contractStyles.title, children: title2 }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: contractStyles.subtitle, children: subtitle2 }),
                parties.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$2.empty, children: "No active fulfillments right now." }) : /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: styles$2.list, children: parties.map((party2) => /* @__PURE__ */ jsxRuntimeExports.jsx(
                  PartyRow,
                  {
                    party: party2,
                    quantityLabel: quantityLabel2
                  },
                  party2.id
                )) }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                  "div",
                  {
                    className: onPauseToggle ? contractStyles.actionsSplit : contractStyles.actions,
                    children: [
                      onPauseToggle ? /* @__PURE__ */ jsxRuntimeExports.jsxs(
                        "button",
                        {
                          type: "button",
                          className: `${contractStyles.actionCompact} ${contractStyles.pauseButton}`,
                          onClick: onPauseToggle,
                          "aria-label": isPaused ? "Resume contract and release reserved slots" : "Pause contract and reserve all empty slots",
                          children: [
                            isPaused ? /* @__PURE__ */ jsxRuntimeExports.jsx(CirclePlay, { size: 16, strokeWidth: 2, "aria-hidden": true }) : /* @__PURE__ */ jsxRuntimeExports.jsx(CirclePause, { size: 16, strokeWidth: 2, "aria-hidden": true }),
                            isPaused ? "Resume" : "Pause"
                          ]
                        }
                      ) : null,
                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "button",
                        {
                          type: "button",
                          className: contractStyles.confirm,
                          onClick: onClose,
                          children: "Close"
                        }
                      )
                    ]
                  }
                )
              ]
            }
          )
        }
      ),
      portalTarget
    );
  }
  function PartyRow({
    party: party2,
    quantityLabel: quantityLabel2
  }) {
    const remaining = useContractCountdown(party2.endsAt);
    const expired = remaining === 0;
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: styles$2.row, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$2.party, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$2.partyLabel, children: "User" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "a",
          {
            className: styles$2.partyLink,
            href: getSellerProfileUrl(party2.partyId),
            target: "_blank",
            rel: "noopener noreferrer",
            children: formatTornUserId(party2.partyId)
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$2.quantity, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$2.quantityLabel, children: quantityLabel2 }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$2.quantityValue, children: party2.quantity.toLocaleString("en-US") })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$2.timer, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$2.timerLabel, children: "Time left" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "span",
          {
            className: `${styles$2.timerValue} ${expired ? styles$2.timerExpired : ""}`,
            children: expired ? "Expiring…" : formatCountdown(remaining)
          }
        )
      ] })
    ] });
  }
  function formatReferralCodeDisplay(code) {
    return code.replace(/[^A-Za-z0-9]/g, "").toUpperCase();
  }
  function normalizeReferralCodeInput(code) {
    return code.replace(/[^A-Za-z0-9]/g, "").toUpperCase();
  }
  function getReferralWindowHoursRemaining(endsAt) {
    if (!endsAt) return null;
    const ms = new Date(endsAt).getTime() - Date.now();
    if (ms <= 0) return 0;
    return Math.ceil(ms / (60 * 60 * 1e3));
  }
  const codeRow = "_codeRow_1b6f7_1";
  const referredBy = "_referredBy_1b6f7_13";
  const enterCodeBlock = "_enterCodeBlock_1b6f7_19";
  const enterCodeHint = "_enterCodeHint_1b6f7_27";
  const enterCodeRow = "_enterCodeRow_1b6f7_34";
  const enterCodeInput = "_enterCodeInput_1b6f7_39";
  const enterCodeInputError = "_enterCodeInputError_1b6f7_52";
  const enterCodeApply = "_enterCodeApply_1b6f7_56";
  const enterCodeError = "_enterCodeError_1b6f7_79";
  const enterCodeSuccess = "_enterCodeSuccess_1b6f7_85";
  const codeLabel = "_codeLabel_1b6f7_91";
  const codeValue = "_codeValue_1b6f7_100";
  const stats = "_stats_1b6f7_110";
  const stat = "_stat_1b6f7_110";
  const list = "_list_1b6f7_143";
  const row = "_row_1b6f7_154";
  const party = "_party_1b6f7_165";
  const partyLabel = "_partyLabel_1b6f7_172";
  const partyLink = "_partyLink_1b6f7_180";
  const progress = "_progress_1b6f7_193";
  const progressLabel = "_progressLabel_1b6f7_201";
  const progressValue = "_progressValue_1b6f7_209";
  const status = "_status_1b6f7_217";
  const status_pending = "_status_pending_1b6f7_227";
  const status_qualified = "_status_qualified_1b6f7_232";
  const status_paid = "_status_paid_1b6f7_237";
  const empty = "_empty_1b6f7_242";
  const styles$1 = {
    codeRow,
    referredBy,
    enterCodeBlock,
    enterCodeHint,
    enterCodeRow,
    enterCodeInput,
    enterCodeInputError,
    enterCodeApply,
    enterCodeError,
    enterCodeSuccess,
    codeLabel,
    codeValue,
    stats,
    stat,
    list,
    row,
    party,
    partyLabel,
    partyLink,
    progress,
    progressLabel,
    progressValue,
    status,
    status_pending,
    status_qualified,
    status_paid,
    empty
  };
  function ReferralsModal({
    summary,
    summaryLoading,
    referrals,
    listLoading,
    onClose,
    onApplyReferralCode,
    applyError,
    applying,
    applySuccess
  }) {
    const referralInputId = reactExports.useId();
    const [referralCodeInput, setReferralCodeInput] = reactExports.useState("");
    reactExports.useEffect(() => {
      const handleKeyDown = (e) => {
        if (e.key === "Escape") onClose();
      };
      window.addEventListener("keydown", handleKeyDown);
      return () => window.removeEventListener("keydown", handleKeyDown);
    }, [onClose]);
    reactExports.useEffect(() => {
      if (applySuccess) {
        setReferralCodeInput("");
      }
    }, [applySuccess]);
    const referralHoursLeft = getReferralWindowHoursRemaining(
      (summary == null ? void 0 : summary.referral_window_ends_at) ?? null
    );
    const handleApplyReferralCode = () => {
      const normalized = normalizeReferralCodeInput(referralCodeInput);
      if (!normalized) return;
      void onApplyReferralCode(normalized);
    };
    return /* @__PURE__ */ jsxRuntimeExports.jsx(
      "div",
      {
        className: contractStyles.overlay,
        role: "presentation",
        onMouseDown: (e) => overlayMouseDownDismiss(e, onClose),
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            className: contractStyles.dialog,
            role: "dialog",
            "aria-modal": "true",
            "aria-labelledby": "tlm-referrals-title",
            onClick: (e) => e.stopPropagation(),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx("h2", { id: "tlm-referrals-title", className: contractStyles.title, children: "Referrals" }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: contractStyles.subtitle, children: [
                "Share your code. Earn ",
                formatExtensionPoints(REFERRAL_REFERRER_BONUS),
                " when someone you refer sells ",
                REFERRAL_LOSSES_THRESHOLD,
                " losses or deposits",
                " ",
                REFERRAL_XANAX_THRESHOLD,
                " Xanax to ARCANE. (Referees get bonus 50k on download)"
              ] }),
              summaryLoading ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$1.empty, children: "Loading…" }) : !summary ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$1.empty, role: "alert", children: "Could not load referral info. Try again later." }) : /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$1.codeRow, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$1.codeLabel, children: "Your invite code" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$1.codeValue, children: formatReferralCodeDisplay(summary.referral_code) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    CopyIdButton,
                    {
                      text: summary.referral_code,
                      label: "Copy referral code",
                      copiedLabel: "Copied"
                    }
                  )
                ] }),
                summary.referred_by_name && /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: styles$1.referredBy, children: [
                  "Referred by ",
                  summary.referred_by_name
                ] }),
                summary.can_enter_code && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$1.enterCodeBlock, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("p", { className: styles$1.enterCodeHint, children: [
                    "Enter a referral code within ",
                    REFERRAL_WINDOW_HOURS,
                    " hours of creating your account",
                    referralHoursLeft !== null && referralHoursLeft > 0 ? ` (${referralHoursLeft}h left)` : "",
                    ". You'll receive ",
                    formatExtensionPoints(REFERRAL_REFEREE_BONUS),
                    "."
                  ] }),
                  /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$1.enterCodeRow, children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "input",
                      {
                        id: referralInputId,
                        className: `${styles$1.enterCodeInput} ${applyError ? styles$1.enterCodeInputError : ""}`,
                        type: "text",
                        autoComplete: "off",
                        spellCheck: false,
                        placeholder: "Referral code",
                        value: referralCodeInput,
                        disabled: applying,
                        onChange: (e) => {
                          setReferralCodeInput(
                            normalizeReferralCodeInput(e.target.value)
                          );
                        },
                        onKeyDown: (e) => {
                          if (e.key === "Enter") {
                            e.preventDefault();
                            handleApplyReferralCode();
                          }
                        }
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "button",
                      {
                        type: "button",
                        className: styles$1.enterCodeApply,
                        onClick: handleApplyReferralCode,
                        disabled: applying || !referralCodeInput.trim(),
                        children: applying ? "Applying…" : "Apply"
                      }
                    )
                  ] }),
                  applyError && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$1.enterCodeError, role: "alert", children: applyError }),
                  applySuccess && /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$1.enterCodeSuccess, role: "status", children: "Referral code applied." })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsxs("dl", { className: styles$1.stats, children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(StatBlock, { label: "Pending", value: String(summary.stats.pending) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    StatBlock,
                    {
                      label: "Qualified",
                      value: String(summary.stats.qualified)
                    }
                  ),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    StatBlock,
                    {
                      label: "Earned",
                      value: formatExtensionPoints(summary.stats.earned_total)
                    }
                  )
                ] }),
                listLoading ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$1.empty, children: "Loading referrals…" }) : referrals.length === 0 ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles$1.empty, children: "No referrals yet. Share your code to get started." }) : /* @__PURE__ */ jsxRuntimeExports.jsx("ul", { className: styles$1.list, children: referrals.map((row2) => /* @__PURE__ */ jsxRuntimeExports.jsx(ReferralRow, { row: row2 }, row2.referee_xid)) })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: contractStyles.actions, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                "button",
                {
                  type: "button",
                  className: contractStyles.confirm,
                  onClick: onClose,
                  children: "Close"
                }
              ) })
            ]
          }
        )
      }
    );
  }
  function ReferralRow({ row: row2 }) {
    const statusLabel = row2.status === "paid" ? "Paid" : row2.status === "qualified" ? "Qualified" : "Pending";
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("li", { className: styles$1.row, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$1.party, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$1.partyLabel, children: "Referee" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "a",
          {
            className: styles$1.partyLink,
            href: getSellerProfileUrl(row2.referee_xid),
            target: "_blank",
            rel: "noopener noreferrer",
            children: row2.referee_display_name || formatTornUserId(row2.referee_xid)
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$1.progress, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: styles$1.progressLabel, children: "Progress" }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs("span", { className: styles$1.progressValue, children: [
          row2.losses_count,
          "/",
          REFERRAL_LOSSES_THRESHOLD,
          " losses ·",
          " ",
          row2.xanax_deposited,
          "/",
          REFERRAL_XANAX_THRESHOLD,
          " Xanax"
        ] })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("span", { className: `${styles$1.status} ${styles$1[`status_${row2.status}`]}`, children: statusLabel })
    ] });
  }
  function StatBlock({ label: label2, value }) {
    return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles$1.stat, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("dt", { children: label2 }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("dd", { children: value })
    ] });
  }
  const CACHE_KEY_PREFIX = "insurance_perks_cache_";
  const CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
  function cacheKey(tornXid) {
    return `${CACHE_KEY_PREFIX}${tornXid ?? "guest"}`;
  }
  function readInsurancePerksCacheSync(tornXid) {
    if (typeof localStorage === "undefined") return null;
    try {
      const raw = localStorage.getItem(cacheKey(tornXid));
      if (!raw) return null;
      const parsed = JSON.parse(raw);
      if (typeof parsed.fetchedAt !== "number" || !Array.isArray(parsed.odReductionPercents) || !parsed.effectiveMultipliers) {
        return null;
      }
      return parsed;
    } catch {
      return null;
    }
  }
  function isInsurancePerksCacheFresh(cache, now2 = Date.now()) {
    if (!cache) return false;
    return now2 - cache.fetchedAt < CACHE_TTL_MS;
  }
  async function loadInsurancePerksCache(tornXid) {
    const sync = readInsurancePerksCacheSync(tornXid);
    if (sync) return sync;
    const key = cacheKey(tornXid);
    const stored = await getPlatformRuntime().storage.get(
      key
    );
    if (!stored || typeof stored.fetchedAt !== "number") return null;
    return stored;
  }
  async function saveInsurancePerksCache(tornXid, cache) {
    const key = cacheKey(tornXid);
    if (typeof localStorage !== "undefined") {
      localStorage.setItem(key, JSON.stringify(cache));
    }
    await getPlatformRuntime().storage.set(key, cache);
  }
  function useInsurancePerks(tornXid, enabled) {
    const [loading, setLoading] = reactExports.useState(false);
    const [error2, setError] = reactExports.useState(null);
    const [odReductionPercents, setOdReductionPercents] = reactExports.useState([]);
    const [effectiveMultipliers, setEffectiveMultipliers] = reactExports.useState(null);
    const applyCache = reactExports.useCallback((cache) => {
      setOdReductionPercents(cache.odReductionPercents);
      setEffectiveMultipliers(cache.effectiveMultipliers);
      setError(null);
    }, []);
    const fetchFresh = reactExports.useCallback(async () => {
      const apiKey = await getPlatformRuntime().auth.getApiKey();
      if (!apiKey) {
        setError("Sign in with your Torn API key to view insurance.");
        setEffectiveMultipliers(null);
        return;
      }
      setLoading(true);
      setError(null);
      try {
        const perks = await getPlatformRuntime().tornMarket.fetchUserPerks();
        const percents = parseOdRiskReductionPercents(perks);
        const multipliers = computeEffectiveMultipliers(percents);
        const cache = {
          fetchedAt: Date.now(),
          odReductionPercents: percents,
          effectiveMultipliers: multipliers
        };
        await saveInsurancePerksCache(tornXid, cache);
        applyCache(cache);
      } catch (err) {
        const message = isTornPerksPermissionError(err) ? err.message : err instanceof Error ? err.message : "Could not load Torn perks";
        setError(message);
        setEffectiveMultipliers(null);
      } finally {
        setLoading(false);
      }
    }, [applyCache, tornXid]);
    const refresh = reactExports.useCallback(async () => {
      await fetchFresh();
    }, [fetchFresh]);
    reactExports.useEffect(() => {
      if (!enabled) {
        setLoading(false);
        return;
      }
      let cancelled = false;
      void (async () => {
        const cached = await loadInsurancePerksCache(tornXid);
        if (cancelled) return;
        if (cached && isInsurancePerksCacheFresh(cached)) {
          applyCache(cached);
          setLoading(false);
          return;
        }
        await fetchFresh();
      })();
      return () => {
        cancelled = true;
      };
    }, [enabled, tornXid, applyCache, fetchFresh]);
    return {
      loading,
      error: error2,
      odReductionPercents,
      effectiveMultipliers,
      refresh
    };
  }
  const ORDERS_KEY_PREFIX$3 = "bounty_orders_";
  function ordersKey$3(tornXid) {
    return tornXid == null ? `${ORDERS_KEY_PREFIX$3}guest` : `${ORDERS_KEY_PREFIX$3}${tornXid}`;
  }
  function ordersSyncKey(tornXid) {
    return ordersKey$3(tornXid);
  }
  function isActiveBountyOrder(value) {
    if (!value || typeof value !== "object") return false;
    const o = value;
    return typeof o.id === "string" && typeof o.buyerId === "number" && typeof o.quantity === "number" && typeof o.quantityRemaining === "number" && Array.isArray(o.targetIds) && o.targetIds.every((id2) => typeof id2 === "number") && typeof o.bountyValueTorn === "number" && typeof o.escrowedTotal === "number" && (o.status === "open" || o.status === "cancelled" || o.status === "filled") && typeof o.createdAt === "number" && (o.activeContracts === void 0 || Array.isArray(o.activeContracts) && o.activeContracts.every(
      (c) => c && typeof c === "object" && typeof c.id === "string" && typeof c.partyId === "number" && typeof c.quantity === "number" && typeof c.endsAt === "number"
    ));
  }
  function normalizeOrder(order) {
    return {
      ...order,
      activeContracts: order.activeContracts ?? []
    };
  }
  function parseOrders$3(raw) {
    if (!Array.isArray(raw)) return [];
    return raw.filter(isActiveBountyOrder).map(normalizeOrder);
  }
  function readOrdersSync$3(tornXid) {
    try {
      const raw = readLocalStorageWithMigration(
        localStorage,
        ordersSyncKey(tornXid)
      );
      if (!raw) return [];
      return parseOrders$3(JSON.parse(raw));
    } catch {
      return [];
    }
  }
  function writeOrdersSync$3(tornXid, orders) {
    try {
      writeLocalStorageCurrent(
        localStorage,
        ordersSyncKey(tornXid),
        JSON.stringify(orders)
      );
    } catch {
    }
  }
  function readStoredBountyOrdersSync(tornXid) {
    return readOrdersSync$3(tornXid).filter(isVisibleBountyMarketOrder);
  }
  async function loadBountyOrders(tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        ordersKey$3(tornXid)
      );
      const orders = parseOrders$3(raw).filter(isVisibleBountyMarketOrder);
      writeOrdersSync$3(tornXid, orders);
      return orders;
    } catch {
      return readStoredBountyOrdersSync(tornXid);
    }
  }
  async function saveBountyOrders(tornXid, orders) {
    writeOrdersSync$3(tornXid, orders);
    try {
      await getPlatformRuntime().storage.set(ordersKey$3(tornXid), orders);
    } catch {
    }
  }
  const ORDERS_KEY_PREFIX$2 = "productivity_boost_";
  function ordersKey$2(tornXid) {
    return tornXid == null ? `${ORDERS_KEY_PREFIX$2}guest` : `${ORDERS_KEY_PREFIX$2}${tornXid}`;
  }
  function isActiveProductivityBoost(value) {
    if (!value || typeof value !== "object") return false;
    const o = value;
    return typeof o.id === "string" && typeof o.companyId === "number" && typeof o.priceTorn === "number" && typeof o.escrowedPts === "number" && o.status === "open" && typeof o.createdAt === "number";
  }
  function parseOrders$2(raw) {
    if (!Array.isArray(raw)) return [];
    return raw.filter(isActiveProductivityBoost);
  }
  function readOrdersSync$2(tornXid) {
    try {
      const raw = readLocalStorageWithMigration(localStorage, ordersKey$2(tornXid));
      if (!raw) return [];
      return parseOrders$2(JSON.parse(raw));
    } catch {
      return [];
    }
  }
  function writeOrdersSync$2(tornXid, orders) {
    try {
      writeLocalStorageCurrent(
        localStorage,
        ordersKey$2(tornXid),
        JSON.stringify(orders)
      );
    } catch {
    }
  }
  function readStoredProductivityBoostsSync(tornXid) {
    return readOrdersSync$2(tornXid).filter((o) => o.status === "open");
  }
  async function loadProductivityBoosts(tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        ordersKey$2(tornXid)
      );
      const orders = parseOrders$2(raw).filter((o) => o.status === "open");
      writeOrdersSync$2(tornXid, orders);
      return orders;
    } catch {
      return readStoredProductivityBoostsSync(tornXid);
    }
  }
  async function saveProductivityBoosts(tornXid, orders) {
    writeOrdersSync$2(tornXid, orders);
    try {
      await getPlatformRuntime().storage.set(ordersKey$2(tornXid), orders);
    } catch {
    }
  }
  function orderRowToActive$2(row2) {
    return {
      id: row2.id,
      targetUserId: row2.target_id,
      priceTorn: row2.price_torn,
      escrowedPts: row2.escrowed_total,
      status: "open",
      createdAt: Date.parse(row2.created_at) || Date.now(),
      buyerXid: row2.buyer_xid
    };
  }
  function progressToActive$2(row2) {
    const endsAt = row2.ends_at ? new Date(row2.ends_at).getTime() : null;
    return {
      id: row2.id,
      targetUserId: row2.target_id,
      priceTorn: row2.price_torn,
      escrowedPts: row2.escrowed_total,
      status: "open",
      createdAt: Date.parse(row2.created_at) || Date.now(),
      inProgress: endsAt != null,
      endsAt,
      contractId: row2.contract_id,
      fulfillerXid: row2.fulfiller_xid
    };
  }
  function contractRowToActive(row2) {
    return {
      id: row2.id,
      targetUserId: row2.target_id,
      priceTorn: 0,
      escrowedPts: row2.payout_amount,
      status: "open",
      createdAt: Date.parse(row2.accepted_at) || Date.now()
    };
  }
  function useEmbargoMarket({
    session,
    useBackend,
    balance,
    requireAuthOrPrompt,
    enqueueAuthAction,
    getApiKey,
    onActivated,
    onSettled,
    noteContractCompleted,
    onCompleted
  }) {
    const [modalOpen, setModalOpen] = reactExports.useState(false);
    const [pending, setPending] = reactExports.useState(null);
    const [myOrders, setMyOrders] = reactExports.useState([]);
    const [listings, setListings] = reactExports.useState([]);
    const [activeFulfillment, setActiveFulfillment] = reactExports.useState(null);
    const [fulfillmentEndsAt2, setFulfillmentEndsAt] = reactExports.useState(
      null
    );
    const [contractId, setContractId] = reactExports.useState(null);
    const [turnInState, setTurnInState] = reactExports.useState("idle");
    const [turnInError2, setTurnInError] = reactExports.useState(null);
    const [pendingCancel, setPendingCancel] = reactExports.useState(
      null
    );
    const turnInFlightRef = reactExports.useRef(false);
    const clearFulfillment = reactExports.useCallback(() => {
      setActiveFulfillment(null);
      setFulfillmentEndsAt(null);
      setContractId(null);
      setTurnInState("idle");
      setTurnInError(null);
    }, []);
    const refresh = reactExports.useCallback(
      async (activeSession) => {
        const supabase2 = getSupabase(activeSession);
        try {
          await releaseMyStaleEngagements(supabase2);
        } catch {
        }
        const [openOrders, myProgress, activeContract] = await Promise.all([
          fetchOpenEmbargoOrders(supabase2),
          fetchMyEmbargoOrdersProgress(supabase2),
          fetchMyActiveEmbargoContract(supabase2)
        ]);
        setMyOrders(myProgress.map(progressToActive$2));
        setListings(openOrders.map(orderRowToActive$2));
        if ((activeContract == null ? void 0 : activeContract.id) && activeContract.status === "active") {
          setContractId(activeContract.id);
          setActiveFulfillment(contractRowToActive(activeContract));
          setFulfillmentEndsAt(new Date(activeContract.ends_at).getTime());
        } else {
          clearFulfillment();
        }
      },
      [clearFulfillment]
    );
    reactExports.useEffect(() => {
      if (useBackend && session) {
        void refresh(session).catch(() => {
        });
      } else {
        setMyOrders([]);
        setListings([]);
        clearFulfillment();
      }
    }, [session == null ? void 0 : session.torn_xid, useBackend]);
    const secondsRemaining = useContractCountdown(
      fulfillmentEndsAt2,
      reactExports.useCallback(() => {
        if (session) void refresh(session).catch(() => {
        });
      }, [session, refresh])
    );
    const timerActive = fulfillmentEndsAt2 != null && secondsRemaining > 0;
    const showContractPanel = timerActive && activeFulfillment != null;
    const open = reactExports.useCallback(() => {
      if (!requireAuthOrPrompt()) return;
      setModalOpen(true);
    }, [requireAuthOrPrompt]);
    const proceed = reactExports.useCallback((order) => {
      setPending(order);
    }, []);
    const confirmBack = reactExports.useCallback(() => {
      setPending(null);
    }, []);
    const confirm2 = reactExports.useCallback(() => {
      const order = pending;
      if (!order) return;
      enqueueAuthAction(async (activeSession) => {
        const supabase2 = getSupabase(activeSession);
        await createEmbargoOrder(
          supabase2,
          order.targetUserId,
          order.priceTorn,
          order.totalCostPts
        );
        setPending(null);
        setModalOpen(false);
        await refresh(activeSession);
        onSettled();
      });
    }, [pending, enqueueAuthAction, refresh, onSettled]);
    const take = reactExports.useCallback(
      (listing) => {
        enqueueAuthAction(async (activeSession) => {
          const contract = await acceptEmbargoContract(
            getSupabase(activeSession),
            listing.id
          );
          setContractId(contract.id);
          setActiveFulfillment(contractRowToActive(contract));
          setFulfillmentEndsAt(new Date(contract.ends_at).getTime());
          setTurnInState("idle");
          setTurnInError(null);
          await refresh(activeSession);
          onActivated();
        });
      },
      [enqueueAuthAction, refresh, onActivated]
    );
    const turnIn = reactExports.useCallback(async () => {
      if (turnInFlightRef.current) return;
      if (!session || !contractId) {
        setTurnInError("No active embargo contract to verify.");
        return;
      }
      turnInFlightRef.current = true;
      setTurnInState("loading");
      setTurnInError(null);
      try {
        const apiKey = await getApiKey();
        if (!apiKey) {
          setTurnInError("Connect your Torn API key to verify the embargo.");
          return;
        }
        const { contract } = await pollEmbargoContract(
          getSupabase(session),
          contractId,
          apiKey
        );
        if (contract.status === "completed") {
          if (activeFulfillment) {
            onCompleted({
              targetUserId: activeFulfillment.targetUserId,
              payout: activeFulfillment.escrowedPts
            });
          }
          clearFulfillment();
          noteContractCompleted();
          onSettled();
          await refresh(session);
        } else if (contract.status !== "active") {
          clearFulfillment();
          setTurnInError("Embargo was not verified before the timer expired.");
          await refresh(session);
        } else {
          setActiveFulfillment(contractRowToActive(contract));
          setTurnInError(
            "No embargo on this target found yet. Use the company special, then turn in again."
          );
        }
      } catch (e) {
        setTurnInError(e instanceof Error ? e.message : "Verification failed.");
      } finally {
        turnInFlightRef.current = false;
        setTurnInState("idle");
      }
    }, [
      session,
      contractId,
      activeFulfillment,
      getApiKey,
      clearFulfillment,
      noteContractCompleted,
      onCompleted,
      onSettled,
      refresh
    ]);
    const requestCancel = reactExports.useCallback((embargo) => {
      setPendingCancel(embargo);
    }, []);
    const cancelDismiss = reactExports.useCallback(() => {
      setPendingCancel(null);
    }, []);
    const cancelConfirm = reactExports.useCallback(() => {
      const order = pendingCancel;
      if (!order) return;
      enqueueAuthAction(async (activeSession) => {
        await cancelEmbargoOrder(getSupabase(activeSession), order.id);
        setPendingCancel(null);
        await refresh(activeSession);
        onSettled();
      });
    }, [pendingCancel, enqueueAuthAction, refresh, onSettled]);
    return {
      modalOpen,
      setModalOpen,
      pending,
      setPending,
      active: myOrders,
      listings,
      availableBalance: balance,
      activeFulfillment,
      secondsRemaining,
      timerActive,
      showContractPanel,
      turnInState,
      turnInError: turnInError2,
      pendingCancel,
      open,
      proceed,
      confirmBack,
      confirm: confirm2,
      take,
      turnIn,
      requestCancel,
      cancelDismiss,
      cancelConfirm,
      refresh
    };
  }
  const REPORT_KEY_PREFIX$1 = "references_report_";
  const SCAN_DEBOUNCE_MS$1 = 400;
  function reportKey$1(targetId) {
    return `${REPORT_KEY_PREFIX$1}${targetId}`;
  }
  async function loadScrapedReferencesReport(targetId) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        reportKey$1(targetId)
      );
      if (raw && typeof raw === "object" && Number(raw.targetId) === targetId && Array.isArray(raw.factionHistory) && Array.isArray(raw.employmentHistory)) {
        return raw;
      }
      return null;
    } catch {
      return null;
    }
  }
  const HISTORY_ROW_RE = /^(.+?)\s*:\s*(\d{2}-\d{2}-\d{4})\s*>\s*(Present|\d{2}-\d{2}-\d{4})$/;
  function parseHistoryList(list2) {
    const rows = [];
    const items = Array.from(list2.querySelectorAll("li"));
    for (const li of items) {
      if (li.querySelector("u")) continue;
      const text2 = (li.textContent ?? "").replace(/\s+/g, " ").trim();
      if (!text2) continue;
      const match = text2.match(HISTORY_ROW_RE);
      if (match) {
        rows.push({ name: match[1].trim(), from: match[2], to: match[3] });
      } else {
        rows.push({ name: text2, from: "", to: "" });
      }
    }
    return rows;
  }
  function parseReportFromMsg$1(msg) {
    var _a2, _b, _c;
    const text2 = (msg.textContent ?? "").toLowerCase();
    if (!text2.includes("employment and faction history of")) return null;
    const link2 = msg.querySelector('a[href*="XID="]');
    const xidMatch = (_a2 = link2 == null ? void 0 : link2.getAttribute("href")) == null ? void 0 : _a2.match(/XID=(\d+)/i);
    const targetId = xidMatch ? Number(xidMatch[1]) : NaN;
    if (!Number.isFinite(targetId) || targetId <= 0) return null;
    let factionHistory = [];
    let employmentHistory = [];
    const lists = Array.from(
      msg.querySelectorAll("ul.job-info")
    );
    for (const list2 of lists) {
      const heading2 = (((_b = list2.querySelector("u")) == null ? void 0 : _b.textContent) ?? "").toLowerCase();
      if (heading2.includes("faction")) {
        factionHistory = parseHistoryList(list2);
      } else if (heading2.includes("employment")) {
        employmentHistory = parseHistoryList(list2);
      }
    }
    if (factionHistory.length === 0 && employmentHistory.length === 0) {
      return null;
    }
    return {
      targetId,
      targetName: ((_c = link2 == null ? void 0 : link2.textContent) == null ? void 0 : _c.trim()) || null,
      scrapedAt: Date.now(),
      factionHistory,
      employmentHistory
    };
  }
  const lastSavedSignature$1 = /* @__PURE__ */ new Map();
  function reportSignature$1(report) {
    return JSON.stringify([
      report.targetId,
      report.factionHistory,
      report.employmentHistory
    ]);
  }
  const reportListeners$1 = /* @__PURE__ */ new Set();
  function subscribeScrapedReferencesReport(listener) {
    reportListeners$1.add(listener);
    return () => {
      reportListeners$1.delete(listener);
    };
  }
  function notifyReportSaved$1(targetId) {
    for (const listener of Array.from(reportListeners$1)) {
      try {
        listener(targetId);
      } catch {
      }
    }
  }
  function scanForReports$1() {
    const containers = document.querySelectorAll(
      ".specials-confirm-cont .msg, .specials-confirm-cont"
    );
    for (const container of Array.from(containers)) {
      let report = null;
      try {
        report = parseReportFromMsg$1(container);
      } catch {
        report = null;
      }
      if (!report) continue;
      const signature = reportSignature$1(report);
      if (lastSavedSignature$1.get(report.targetId) === signature) continue;
      lastSavedSignature$1.set(report.targetId, signature);
      const targetId = report.targetId;
      void getPlatformRuntime().storage.set(reportKey$1(targetId), report).then(() => {
        notifyReportSaved$1(targetId);
      }).catch(() => {
        lastSavedSignature$1.delete(targetId);
      });
    }
  }
  let scraperStarted$1 = false;
  function initReferencesScraper() {
    if (scraperStarted$1) return;
    try {
      if (!/(^|\.)torn\.com$/i.test(location.hostname)) return;
      if (!location.pathname.includes("/companies.php")) return;
    } catch {
      return;
    }
    scraperStarted$1 = true;
    let debounce;
    const scheduleScan = () => {
      if (debounce !== void 0) globalThis.clearTimeout(debounce);
      debounce = globalThis.setTimeout(() => {
        debounce = void 0;
        scanForReports$1();
      }, SCAN_DEBOUNCE_MS$1);
    };
    const start = () => {
      scanForReports$1();
      const observer2 = new MutationObserver(scheduleScan);
      observer2.observe(document.body, { childList: true, subtree: true });
    };
    if (document.body) {
      start();
    } else {
      document.addEventListener("DOMContentLoaded", start, { once: true });
    }
  }
  function orderRowToActive$1(row2) {
    return {
      id: row2.id,
      targetUserId: row2.target_id,
      priceTorn: row2.price_torn,
      escrowedPts: row2.escrowed_total,
      status: "open",
      createdAt: Date.parse(row2.created_at) || Date.now(),
      buyerXid: row2.buyer_xid
    };
  }
  function progressToActive$1(row2) {
    const endsAt = row2.ends_at ? new Date(row2.ends_at).getTime() : null;
    return {
      id: row2.id,
      targetUserId: row2.target_id,
      priceTorn: row2.price_torn,
      escrowedPts: row2.escrowed_total,
      status: "open",
      createdAt: Date.parse(row2.created_at) || Date.now(),
      inProgress: endsAt != null,
      endsAt,
      contractId: row2.contract_id,
      fulfillerXid: row2.fulfiller_xid,
      report: row2.report ?? null
    };
  }
  function useReferencesMarket({
    session,
    useBackend,
    balance,
    requireAuthOrPrompt,
    enqueueAuthAction,
    getApiKey,
    onActivated,
    onSettled,
    noteContractCompleted,
    onCompleted
  }) {
    const [modalOpen, setModalOpen] = reactExports.useState(false);
    const [pending, setPending] = reactExports.useState(
      null
    );
    const [myOrders, setMyOrders] = reactExports.useState([]);
    const [listings, setListings] = reactExports.useState([]);
    const [activeFulfillment, setActiveFulfillment] = reactExports.useState(null);
    const [fulfillmentEndsAt2, setFulfillmentEndsAt] = reactExports.useState(
      null
    );
    const [contractId, setContractId] = reactExports.useState(null);
    const [turnInState, setTurnInState] = reactExports.useState("idle");
    const [turnInError2, setTurnInError] = reactExports.useState(null);
    const [pendingCancel, setPendingCancel] = reactExports.useState(
      null
    );
    const turnInFlightRef = reactExports.useRef(false);
    const clearFulfillment = reactExports.useCallback(() => {
      setActiveFulfillment(null);
      setFulfillmentEndsAt(null);
      setContractId(null);
      setTurnInState("idle");
      setTurnInError(null);
    }, []);
    const refresh = reactExports.useCallback(
      async (activeSession) => {
        const supabase2 = getSupabase(activeSession);
        try {
          await releaseMyStaleEngagements(supabase2);
        } catch {
        }
        const [openOrders, myProgress, activeContract] = await Promise.all([
          fetchOpenReferencesOrders(supabase2),
          fetchMyReferencesOrdersProgress(supabase2),
          fetchMyActiveReferencesContract(supabase2)
        ]);
        setMyOrders(myProgress.map(progressToActive$1));
        setListings(openOrders.map(orderRowToActive$1));
        if ((activeContract == null ? void 0 : activeContract.id) && activeContract.status === "active") {
          setContractId(activeContract.id);
          setActiveFulfillment({
            id: activeContract.id,
            targetUserId: activeContract.target_id,
            priceTorn: 0,
            escrowedPts: activeContract.payout_amount,
            status: "open",
            createdAt: Date.parse(activeContract.accepted_at) || Date.now()
          });
          setFulfillmentEndsAt(new Date(activeContract.ends_at).getTime());
        } else {
          clearFulfillment();
        }
      },
      [clearFulfillment]
    );
    reactExports.useEffect(() => {
      if (useBackend && session) {
        void refresh(session).catch(() => {
        });
      } else {
        setMyOrders([]);
        setListings([]);
        clearFulfillment();
      }
    }, [session == null ? void 0 : session.torn_xid, useBackend]);
    const secondsRemaining = useContractCountdown(
      fulfillmentEndsAt2,
      reactExports.useCallback(() => {
        if (session) void refresh(session).catch(() => {
        });
      }, [session, refresh])
    );
    const timerActive = fulfillmentEndsAt2 != null && secondsRemaining > 0;
    const showContractPanel = timerActive && activeFulfillment != null;
    const open = reactExports.useCallback(() => {
      if (!requireAuthOrPrompt()) return;
      setModalOpen(true);
    }, [requireAuthOrPrompt]);
    const proceed = reactExports.useCallback((order) => {
      setPending(order);
    }, []);
    const confirmBack = reactExports.useCallback(() => {
      setPending(null);
    }, []);
    const confirm2 = reactExports.useCallback(() => {
      const order = pending;
      const targetId = order == null ? void 0 : order.targetUserIds[0];
      if (!order || targetId == null) return;
      enqueueAuthAction(async (activeSession) => {
        const supabase2 = getSupabase(activeSession);
        await createReferencesOrder(
          supabase2,
          targetId,
          order.priceTorn,
          order.totalCostPts
        );
        setPending(null);
        setModalOpen(false);
        await refresh(activeSession);
        onSettled();
      });
    }, [pending, enqueueAuthAction, refresh, onSettled]);
    const take = reactExports.useCallback(
      (listing) => {
        enqueueAuthAction(async (activeSession) => {
          const contract = await acceptReferencesContract(
            getSupabase(activeSession),
            listing.id
          );
          setContractId(contract.id);
          setActiveFulfillment({
            id: contract.id,
            targetUserId: contract.target_id,
            priceTorn: 0,
            escrowedPts: contract.payout_amount,
            status: "open",
            createdAt: Date.parse(contract.accepted_at) || Date.now()
          });
          setFulfillmentEndsAt(new Date(contract.ends_at).getTime());
          setTurnInState("idle");
          setTurnInError(null);
          await refresh(activeSession);
          onActivated();
        });
      },
      [enqueueAuthAction, refresh, onActivated]
    );
    const turnIn = reactExports.useCallback(async () => {
      if (turnInFlightRef.current) return;
      const targetId = (activeFulfillment == null ? void 0 : activeFulfillment.targetUserId) ?? null;
      if (!session || !contractId || targetId == null) {
        setTurnInError("No active references contract to verify.");
        return;
      }
      turnInFlightRef.current = true;
      setTurnInState("loading");
      setTurnInError(null);
      try {
        const apiKey = await getApiKey();
        if (!apiKey) {
          setTurnInError("Connect your Torn API key to verify the references.");
          return;
        }
        const report = await loadScrapedReferencesReport(targetId);
        if (!report) {
          setTurnInError(
            "No report captured yet. Use the company special on the target and keep the results on screen, then turn in."
          );
          return;
        }
        const { contract, report_stored } = await pollReferencesContract(
          getSupabase(session),
          contractId,
          apiKey,
          report
        );
        if (contract.status === "completed") {
          onCompleted({
            targetUserId: targetId,
            payout: (activeFulfillment == null ? void 0 : activeFulfillment.escrowedPts) ?? 0
          });
          clearFulfillment();
          noteContractCompleted();
          onSettled();
          await refresh(session);
        } else if (contract.status !== "active") {
          clearFulfillment();
          setTurnInError(
            "References were not delivered before the timer expired."
          );
          await refresh(session);
        } else if (contract.verified < 1) {
          setTurnInError(
            "No job-point spend on this target found yet. Use the company special, then turn in again."
          );
        } else if (!report_stored) {
          setTurnInError(
            "The captured report did not match the target. Re-run the special and turn in again."
          );
        }
      } catch (e) {
        setTurnInError(e instanceof Error ? e.message : "Verification failed.");
      } finally {
        turnInFlightRef.current = false;
        setTurnInState("idle");
      }
    }, [
      session,
      contractId,
      activeFulfillment,
      getApiKey,
      clearFulfillment,
      noteContractCompleted,
      onCompleted,
      onSettled,
      refresh
    ]);
    const turnInRef = reactExports.useRef(turnIn);
    reactExports.useEffect(() => {
      turnInRef.current = turnIn;
    }, [turnIn]);
    const autoTargetId = (activeFulfillment == null ? void 0 : activeFulfillment.targetUserId) ?? null;
    reactExports.useEffect(() => {
      if (!useBackend || !session || !contractId || autoTargetId == null) return;
      const unsubscribe = subscribeScrapedReferencesReport((savedTargetId) => {
        if (savedTargetId !== autoTargetId) return;
        void turnInRef.current();
      });
      return unsubscribe;
    }, [useBackend, session, contractId, autoTargetId]);
    const requestCancel = reactExports.useCallback((order) => {
      setPendingCancel(order);
    }, []);
    const cancelDismiss = reactExports.useCallback(() => {
      setPendingCancel(null);
    }, []);
    const cancelConfirm = reactExports.useCallback(() => {
      const order = pendingCancel;
      if (!order) return;
      enqueueAuthAction(async (activeSession) => {
        await cancelReferencesOrder(
          getSupabase(activeSession),
          order.id
        );
        setPendingCancel(null);
        await refresh(activeSession);
        onSettled();
      });
    }, [pendingCancel, enqueueAuthAction, refresh, onSettled]);
    return {
      modalOpen,
      setModalOpen,
      pending,
      setPending,
      active: myOrders,
      listings,
      availableBalance: balance,
      activeFulfillment,
      secondsRemaining,
      timerActive,
      showContractPanel,
      turnInState,
      turnInError: turnInError2,
      pendingCancel,
      open,
      proceed,
      confirmBack,
      confirm: confirm2,
      take,
      turnIn,
      requestCancel,
      cancelDismiss,
      cancelConfirm,
      refresh
    };
  }
  const REPORT_KEY_PREFIX = "bounty_reveal_report_";
  const SCAN_DEBOUNCE_MS = 400;
  function reportKey(targetId) {
    return `${REPORT_KEY_PREFIX}${targetId}`;
  }
  async function loadScrapedBountyRevealReport(targetId) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        reportKey(targetId)
      );
      if (raw && typeof raw === "object" && Number(raw.targetId) === targetId && Array.isArray(raw.bounties)) {
        return raw;
      }
      return null;
    } catch {
      return null;
    }
  }
  const BOUNTY_ROW_RE = /^(.+?)\s*\[(\d+)\]\s*@\s*\$?([\d,]+)$/;
  function parseBountyList(list2) {
    const rows = [];
    const items = Array.from(list2.querySelectorAll("li"));
    for (const li of items) {
      if (li.querySelector("u")) continue;
      const text2 = (li.textContent ?? "").replace(/\s+/g, " ").trim();
      if (!text2) continue;
      const match = text2.match(BOUNTY_ROW_RE);
      if (match) {
        const reward = Number(match[3].replace(/,/g, ""));
        rows.push({
          name: match[1].trim(),
          listerId: Number(match[2]),
          reward: Number.isFinite(reward) ? reward : 0
        });
      } else {
        rows.push({ name: text2, listerId: null, reward: 0 });
      }
    }
    return rows;
  }
  function parseReportFromMsg(msg) {
    var _a2, _b;
    const text2 = (msg.textContent ?? "").toLowerCase();
    if (!text2.includes("bounties that have been placed on")) return null;
    const link2 = msg.querySelector('a[href*="XID="]');
    const xidMatch = (_a2 = link2 == null ? void 0 : link2.getAttribute("href")) == null ? void 0 : _a2.match(/XID=(\d+)/i);
    const targetId = xidMatch ? Number(xidMatch[1]) : NaN;
    if (!Number.isFinite(targetId) || targetId <= 0) return null;
    let bounties = [];
    const lists = Array.from(
      msg.querySelectorAll("ul.job-info")
    );
    for (const list2 of lists) {
      bounties = bounties.concat(parseBountyList(list2));
    }
    if (bounties.length === 0) return null;
    return {
      targetId,
      targetName: ((_b = link2 == null ? void 0 : link2.textContent) == null ? void 0 : _b.trim()) || null,
      scrapedAt: Date.now(),
      bounties
    };
  }
  const lastSavedSignature = /* @__PURE__ */ new Map();
  function reportSignature(report) {
    return JSON.stringify([report.targetId, report.bounties]);
  }
  const reportListeners = /* @__PURE__ */ new Set();
  function subscribeScrapedBountyRevealReport(listener) {
    reportListeners.add(listener);
    return () => {
      reportListeners.delete(listener);
    };
  }
  function notifyReportSaved(targetId) {
    for (const listener of Array.from(reportListeners)) {
      try {
        listener(targetId);
      } catch {
      }
    }
  }
  function scanForReports() {
    const containers = document.querySelectorAll(
      ".specials-confirm-cont .msg, .specials-confirm-cont"
    );
    for (const container of Array.from(containers)) {
      let report = null;
      try {
        report = parseReportFromMsg(container);
      } catch {
        report = null;
      }
      if (!report) continue;
      const signature = reportSignature(report);
      if (lastSavedSignature.get(report.targetId) === signature) continue;
      lastSavedSignature.set(report.targetId, signature);
      const targetId = report.targetId;
      void getPlatformRuntime().storage.set(reportKey(targetId), report).then(() => {
        notifyReportSaved(targetId);
      }).catch(() => {
        lastSavedSignature.delete(targetId);
      });
    }
  }
  let scraperStarted = false;
  function initBountyRevealScraper() {
    if (scraperStarted) return;
    try {
      if (!/(^|\.)torn\.com$/i.test(location.hostname)) return;
      if (!location.pathname.includes("/companies.php")) return;
    } catch {
      return;
    }
    scraperStarted = true;
    let debounce;
    const scheduleScan = () => {
      if (debounce !== void 0) globalThis.clearTimeout(debounce);
      debounce = globalThis.setTimeout(() => {
        debounce = void 0;
        scanForReports();
      }, SCAN_DEBOUNCE_MS);
    };
    const start = () => {
      scanForReports();
      const observer2 = new MutationObserver(scheduleScan);
      observer2.observe(document.body, { childList: true, subtree: true });
    };
    if (document.body) {
      start();
    } else {
      document.addEventListener("DOMContentLoaded", start, { once: true });
    }
  }
  function orderRowToActive(row2) {
    return {
      id: row2.id,
      targetUserId: row2.target_id,
      priceTorn: row2.price_torn,
      escrowedPts: row2.escrowed_total,
      status: "open",
      createdAt: Date.parse(row2.created_at) || Date.now(),
      buyerXid: row2.buyer_xid
    };
  }
  function progressToActive(row2) {
    const endsAt = row2.ends_at ? new Date(row2.ends_at).getTime() : null;
    return {
      id: row2.id,
      targetUserId: row2.target_id,
      priceTorn: row2.price_torn,
      escrowedPts: row2.escrowed_total,
      status: "open",
      createdAt: Date.parse(row2.created_at) || Date.now(),
      inProgress: endsAt != null,
      endsAt,
      contractId: row2.contract_id,
      fulfillerXid: row2.fulfiller_xid,
      report: row2.report ?? null
    };
  }
  function useBountyRevealMarket({
    session,
    useBackend,
    balance,
    requireAuthOrPrompt,
    enqueueAuthAction,
    getApiKey,
    onActivated,
    onSettled,
    noteContractCompleted,
    onCompleted
  }) {
    const [modalOpen, setModalOpen] = reactExports.useState(false);
    const [pending, setPending] = reactExports.useState(
      null
    );
    const [myOrders, setMyOrders] = reactExports.useState([]);
    const [listings, setListings] = reactExports.useState([]);
    const [activeFulfillment, setActiveFulfillment] = reactExports.useState(null);
    const [fulfillmentEndsAt2, setFulfillmentEndsAt] = reactExports.useState(
      null
    );
    const [contractId, setContractId] = reactExports.useState(null);
    const [turnInState, setTurnInState] = reactExports.useState("idle");
    const [turnInError2, setTurnInError] = reactExports.useState(null);
    const [pendingCancel, setPendingCancel] = reactExports.useState(null);
    const turnInFlightRef = reactExports.useRef(false);
    const clearFulfillment = reactExports.useCallback(() => {
      setActiveFulfillment(null);
      setFulfillmentEndsAt(null);
      setContractId(null);
      setTurnInState("idle");
      setTurnInError(null);
    }, []);
    const refresh = reactExports.useCallback(
      async (activeSession) => {
        const supabase2 = getSupabase(activeSession);
        try {
          await releaseMyStaleEngagements(supabase2);
        } catch {
        }
        const [openOrders, myProgress, activeContract] = await Promise.all([
          fetchOpenBountyRevealOrders(supabase2),
          fetchMyBountyRevealOrdersProgress(supabase2),
          fetchMyActiveBountyRevealContract(supabase2)
        ]);
        setMyOrders(myProgress.map(progressToActive));
        setListings(openOrders.map(orderRowToActive));
        if ((activeContract == null ? void 0 : activeContract.id) && activeContract.status === "active") {
          setContractId(activeContract.id);
          setActiveFulfillment({
            id: activeContract.id,
            targetUserId: activeContract.target_id,
            priceTorn: 0,
            escrowedPts: activeContract.payout_amount,
            status: "open",
            createdAt: Date.parse(activeContract.accepted_at) || Date.now()
          });
          setFulfillmentEndsAt(new Date(activeContract.ends_at).getTime());
        } else {
          clearFulfillment();
        }
      },
      [clearFulfillment]
    );
    reactExports.useEffect(() => {
      if (useBackend && session) {
        void refresh(session).catch(() => {
        });
      } else {
        setMyOrders([]);
        setListings([]);
        clearFulfillment();
      }
    }, [session == null ? void 0 : session.torn_xid, useBackend]);
    const secondsRemaining = useContractCountdown(
      fulfillmentEndsAt2,
      reactExports.useCallback(() => {
        if (session) void refresh(session).catch(() => {
        });
      }, [session, refresh])
    );
    const timerActive = fulfillmentEndsAt2 != null && secondsRemaining > 0;
    const showContractPanel = timerActive && activeFulfillment != null;
    const open = reactExports.useCallback(() => {
      if (!requireAuthOrPrompt()) return;
      setModalOpen(true);
    }, [requireAuthOrPrompt]);
    const proceed = reactExports.useCallback((order) => {
      setPending(order);
    }, []);
    const confirmBack = reactExports.useCallback(() => {
      setPending(null);
    }, []);
    const confirm2 = reactExports.useCallback(() => {
      const order = pending;
      const targetId = order == null ? void 0 : order.targetUserIds[0];
      if (!order || targetId == null) return;
      enqueueAuthAction(async (activeSession) => {
        const supabase2 = getSupabase(activeSession);
        await createBountyRevealOrder(
          supabase2,
          targetId,
          order.priceTorn,
          order.totalCostPts
        );
        setPending(null);
        setModalOpen(false);
        await refresh(activeSession);
        onSettled();
      });
    }, [pending, enqueueAuthAction, refresh, onSettled]);
    const take = reactExports.useCallback(
      (listing) => {
        enqueueAuthAction(async (activeSession) => {
          const contract = await acceptBountyRevealContract(
            getSupabase(activeSession),
            listing.id
          );
          setContractId(contract.id);
          setActiveFulfillment({
            id: contract.id,
            targetUserId: contract.target_id,
            priceTorn: 0,
            escrowedPts: contract.payout_amount,
            status: "open",
            createdAt: Date.parse(contract.accepted_at) || Date.now()
          });
          setFulfillmentEndsAt(new Date(contract.ends_at).getTime());
          setTurnInState("idle");
          setTurnInError(null);
          await refresh(activeSession);
          onActivated();
        });
      },
      [enqueueAuthAction, refresh, onActivated]
    );
    const turnIn = reactExports.useCallback(async () => {
      if (turnInFlightRef.current) return;
      const targetId = (activeFulfillment == null ? void 0 : activeFulfillment.targetUserId) ?? null;
      if (!session || !contractId || targetId == null) {
        setTurnInError("No active bounty reveal contract to verify.");
        return;
      }
      turnInFlightRef.current = true;
      setTurnInState("loading");
      setTurnInError(null);
      try {
        const apiKey = await getApiKey();
        if (!apiKey) {
          setTurnInError("Connect your Torn API key to verify the bounties.");
          return;
        }
        const report = await loadScrapedBountyRevealReport(targetId);
        if (!report) {
          setTurnInError(
            "No report captured yet. Use the company special on the target and keep the results on screen, then turn in."
          );
          return;
        }
        const { contract, report_stored } = await pollBountyRevealContract(
          getSupabase(session),
          contractId,
          apiKey,
          report
        );
        if (contract.status === "completed") {
          onCompleted({
            targetUserId: targetId,
            payout: (activeFulfillment == null ? void 0 : activeFulfillment.escrowedPts) ?? 0
          });
          clearFulfillment();
          noteContractCompleted();
          onSettled();
          await refresh(session);
        } else if (contract.status !== "active") {
          clearFulfillment();
          setTurnInError(
            "Bounties were not delivered before the timer expired."
          );
          await refresh(session);
        } else if (contract.verified < 1) {
          setTurnInError(
            "No job-point spend on this target found yet. Use the company special, then turn in again."
          );
        } else if (!report_stored) {
          setTurnInError(
            "The captured report did not match the target. Re-run the special and turn in again."
          );
        }
      } catch (e) {
        setTurnInError(e instanceof Error ? e.message : "Verification failed.");
      } finally {
        turnInFlightRef.current = false;
        setTurnInState("idle");
      }
    }, [
      session,
      contractId,
      activeFulfillment,
      getApiKey,
      clearFulfillment,
      noteContractCompleted,
      onCompleted,
      onSettled,
      refresh
    ]);
    const turnInRef = reactExports.useRef(turnIn);
    reactExports.useEffect(() => {
      turnInRef.current = turnIn;
    }, [turnIn]);
    const autoTargetId = (activeFulfillment == null ? void 0 : activeFulfillment.targetUserId) ?? null;
    reactExports.useEffect(() => {
      if (!useBackend || !session || !contractId || autoTargetId == null) return;
      const unsubscribe = subscribeScrapedBountyRevealReport((savedTargetId) => {
        if (savedTargetId !== autoTargetId) return;
        void turnInRef.current();
      });
      return unsubscribe;
    }, [useBackend, session, contractId, autoTargetId]);
    const requestCancel = reactExports.useCallback((order) => {
      setPendingCancel(order);
    }, []);
    const cancelDismiss = reactExports.useCallback(() => {
      setPendingCancel(null);
    }, []);
    const cancelConfirm = reactExports.useCallback(() => {
      const order = pendingCancel;
      if (!order) return;
      enqueueAuthAction(async (activeSession) => {
        await cancelBountyRevealOrder(
          getSupabase(activeSession),
          order.id
        );
        setPendingCancel(null);
        await refresh(activeSession);
        onSettled();
      });
    }, [pendingCancel, enqueueAuthAction, refresh, onSettled]);
    return {
      modalOpen,
      setModalOpen,
      pending,
      setPending,
      active: myOrders,
      listings,
      availableBalance: balance,
      activeFulfillment,
      secondsRemaining,
      timerActive,
      showContractPanel,
      turnInState,
      turnInError: turnInError2,
      pendingCancel,
      open,
      proceed,
      confirmBack,
      confirm: confirm2,
      take,
      turnIn,
      requestCancel,
      cancelDismiss,
      cancelConfirm,
      refresh
    };
  }
  const ORDERS_KEY_PREFIX$1 = "flight_delay_";
  function ordersKey$1(tornXid) {
    return tornXid == null ? `${ORDERS_KEY_PREFIX$1}guest` : `${ORDERS_KEY_PREFIX$1}${tornXid}`;
  }
  function isActiveFlightDelay(value) {
    if (!value || typeof value !== "object") return false;
    const o = value;
    return typeof o.id === "string" && typeof o.targetUserId === "number" && typeof o.priceTorn === "number" && typeof o.escrowedPts === "number" && o.status === "open" && typeof o.createdAt === "number";
  }
  function parseOrders$1(raw) {
    if (!Array.isArray(raw)) return [];
    return raw.filter(isActiveFlightDelay);
  }
  function readOrdersSync$1(tornXid) {
    try {
      const raw = readLocalStorageWithMigration(localStorage, ordersKey$1(tornXid));
      if (!raw) return [];
      return parseOrders$1(JSON.parse(raw));
    } catch {
      return [];
    }
  }
  function writeOrdersSync$1(tornXid, orders) {
    try {
      writeLocalStorageCurrent(
        localStorage,
        ordersKey$1(tornXid),
        JSON.stringify(orders)
      );
    } catch {
    }
  }
  function readStoredFlightDelaysSync(tornXid) {
    return readOrdersSync$1(tornXid).filter((o) => o.status === "open");
  }
  async function loadFlightDelays(tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        ordersKey$1(tornXid)
      );
      const orders = parseOrders$1(raw).filter((o) => o.status === "open");
      writeOrdersSync$1(tornXid, orders);
      return orders;
    } catch {
      return readStoredFlightDelaysSync(tornXid);
    }
  }
  async function saveFlightDelays(tornXid, orders) {
    writeOrdersSync$1(tornXid, orders);
    try {
      await getPlatformRuntime().storage.set(ordersKey$1(tornXid), orders);
    } catch {
    }
  }
  const ORDERS_KEY_PREFIX = "simple_services_";
  function ordersKey(tornXid) {
    return tornXid == null ? `${ORDERS_KEY_PREFIX}guest` : `${ORDERS_KEY_PREFIX}${tornXid}`;
  }
  function isActiveSimpleService(value) {
    if (!value || typeof value !== "object") return false;
    const o = value;
    return typeof o.id === "string" && typeof o.kind === "string" && isSimpleServiceId(o.kind) && typeof o.targetUserId === "number" && typeof o.priceTorn === "number" && typeof o.escrowedPts === "number" && o.status === "open" && typeof o.createdAt === "number";
  }
  function parseOrders(raw) {
    if (!Array.isArray(raw)) return [];
    return raw.filter(isActiveSimpleService);
  }
  function readOrdersSync(tornXid) {
    try {
      const raw = readLocalStorageWithMigration(localStorage, ordersKey(tornXid));
      if (!raw) return [];
      return parseOrders(JSON.parse(raw));
    } catch {
      return [];
    }
  }
  function writeOrdersSync(tornXid, orders) {
    try {
      writeLocalStorageCurrent(
        localStorage,
        ordersKey(tornXid),
        JSON.stringify(orders)
      );
    } catch {
    }
  }
  function readStoredSimpleServicesSync(tornXid) {
    return readOrdersSync(tornXid).filter((o) => o.status === "open");
  }
  async function loadSimpleServices(tornXid) {
    try {
      const raw = await getPlatformRuntime().storage.get(
        ordersKey(tornXid)
      );
      const orders = parseOrders(raw).filter((o) => o.status === "open");
      writeOrdersSync(tornXid, orders);
      return orders;
    } catch {
      return readStoredSimpleServicesSync(tornXid);
    }
  }
  async function saveSimpleServices(tornXid, orders) {
    writeOrdersSync(tornXid, orders);
    try {
      await getPlatformRuntime().storage.set(ordersKey(tornXid), orders);
    } catch {
    }
  }
  function hasExpiredActiveBountyChild(orders) {
    const now2 = Date.now();
    return orders.some(
      (order) => order.activeContracts.some((party2) => party2.endsAt <= now2)
    );
  }
  const root = "_root_uz7kd_1";
  const banner = "_banner_uz7kd_24";
  const bannerFeature = "_bannerFeature_uz7kd_62";
  const bannerFeatureButton = "_bannerFeatureButton_uz7kd_81";
  const styles = {
    root,
    banner,
    bannerFeature,
    bannerFeatureButton
  };
  function bountyOrderRowToActive(order) {
    return {
      id: order.id,
      buyerId: order.buyer_xid,
      quantity: order.quantity,
      quantityRemaining: order.quantity_remaining,
      targetIds: [order.target_id],
      bountyValueTorn: Number(order.bounty_value_torn),
      escrowedTotal: Number(order.escrowed_total),
      status: order.status,
      createdAt: new Date(order.created_at).getTime(),
      activeContracts: []
    };
  }
  function bountyContractToActiveFulfillment(contract) {
    return {
      order: {
        id: contract.bounty_order_id,
        buyerId: contract.buyer_xid,
        quantity: contract.quantity,
        quantityRemaining: contract.quantity_remaining,
        targetIds: [contract.target_id],
        bountyValueTorn: Number(contract.bounty_value_torn),
        escrowedTotal: Number(contract.payout_amount),
        status: contract.status === "active" ? "open" : "filled",
        createdAt: new Date(contract.created_at).getTime(),
        activeContracts: []
      },
      targetId: contract.target_id,
      slotsTotal: contract.quantity,
      slotsRemaining: contract.quantity_remaining,
      slotsVerified: contract.quantity_verified
    };
  }
  function isLossContractRow(contract) {
    return "losses_verified" in contract;
  }
  function isBountyContractRow(contract) {
    return "quantity_verified" in contract;
  }
  const STALE_BOARD_ERROR_FRAGMENTS = [
    "order is not open",
    "request is not open",
    "order not found",
    "request not found",
    "quantity exceeds remaining on order",
    "quantity exceeds remaining on request",
    "request already has active fulfillment"
  ];
  function isStaleBoardError(err) {
    const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
    return STALE_BOARD_ERROR_FRAGMENTS.some((fragment) => msg.includes(fragment));
  }
  const ALERT_SEEN_PRUNE_TTL_MS = 5 * 6e4;
  function App() {
    var _a2, _b;
    const platform = getPlatformRuntime();
    const auth2 = useAuth();
    const session = auth2.session;
    const [sidebarOpen, setSidebarOpen] = reactExports.useState(isWebPlatform());
    const [mode, setMode] = reactExports.useState("selling");
    const [settingsOpen, setSettingsOpen] = reactExports.useState(false);
    const {
      alertThreshold,
      alertEscapeThreshold,
      alertStalemateThreshold,
      alertWithdrawalThreshold,
      alertBountyThreshold,
      alertEmbargoThreshold,
      alertProductivityThreshold,
      alertFlightDelayThreshold,
      alertSimpleServiceThresholds,
      alertVolume,
      settingsProps: alertSettings
    } = useAlertThresholds((session == null ? void 0 : session.torn_xid) ?? null);
    const hasMarketAlerts = alertThreshold !== null || alertEscapeThreshold !== null || alertStalemateThreshold !== null || alertWithdrawalThreshold !== null || alertBountyThreshold !== null || alertEmbargoThreshold !== null || alertProductivityThreshold !== null || alertFlightDelayThreshold !== null || Object.values(alertSimpleServiceThresholds).some((v) => v !== null);
    const loadBoard = sidebarOpen || hasMarketAlerts;
    const market = useMarketData(auth2.session, auth2.configured, { loadBoard });
    const useBackend = market.useBackend;
    const [offlineBalance, setOfflineBalance] = reactExports.useState(DEFAULT_USER_BALANCE);
    const [offlineMarketListings, setOfflineMarketListings] = reactExports.useState(BUYING_LISTINGS);
    const [offlineBuyerOrders, setOfflineBuyerOrders] = reactExports.useState(
      []
    );
    const [offlineContractEndsAt, setOfflineContractEndsAt] = reactExports.useState(null);
    const [offlineActiveContract, setOfflineActiveContract] = reactExports.useState(null);
    const [offlineRedeemingListings, setOfflineRedeemingListings] = reactExports.useState(
      () => REDEEMING_LISTINGS
    );
    const [offlineOwnRedeemingIds, setOfflineOwnRedeemingIds] = reactExports.useState(
      () => /* @__PURE__ */ new Set()
    );
    const [offlineRedeemingEndsAt, setOfflineRedeemingEndsAt] = reactExports.useState(null);
    const [offlineActiveRedeeming, setOfflineActiveRedeeming] = reactExports.useState(null);
    const [offlineBountyEndsAt, setOfflineBountyEndsAt] = reactExports.useState(
      null
    );
    const [offlineActiveBountyFulfillment, setOfflineActiveBountyFulfillment] = reactExports.useState(null);
    const [pendingListing, setPendingListing] = reactExports.useState(
      null
    );
    const [pendingBuyerOrder, setPendingBuyerOrder] = reactExports.useState(null);
    const [buyerFormResetKey, setBuyerFormResetKey] = reactExports.useState(0);
    const [buyerConfirmError, setBuyerConfirmError] = reactExports.useState(
      null
    );
    const [buyerConfirmLoading, setBuyerConfirmLoading] = reactExports.useState(false);
    const [equipmentPermissionError, setEquipmentPermissionError] = reactExports.useState(false);
    const [pendingCancelBuyerOrder, setPendingCancelBuyerOrder] = reactExports.useState(null);
    const [depositModalOpen, setDepositModalOpen] = reactExports.useState(false);
    const [balanceModalView, setBalanceModalView] = reactExports.useState("deposit");
    const [pendingRedeemingListing, setPendingRedeemingListing] = reactExports.useState(null);
    const [pendingCancelRedeeming, setPendingCancelRedeeming] = reactExports.useState(null);
    const [inProgressView, setInProgressView] = reactExports.useState(
      null
    );
    const [buyerOrderProgressView, setBuyerOrderProgressView] = reactExports.useState(null);
    const [dismissedBuyerOrderIds, setDismissedBuyerOrderIds] = reactExports.useState(() => readDismissedBuyerOrderIds(null));
    const [dismissedReferencesIds, setDismissedReferencesIds] = reactExports.useState(() => readDismissedReferencesIds(null));
    const [dismissedBountyRevealIds, setDismissedBountyRevealIds] = reactExports.useState(() => readDismissedBountyRevealIds(null));
    const [actionError, setActionError] = reactExports.useState(null);
    const {
      referralsModalOpen,
      referralSummary,
      referralList,
      referralSummaryLoading,
      referralsListLoading,
      referralApplyError,
      referralApplying,
      referralApplySuccess,
      handleOpenReferrals,
      handleCloseReferrals,
      handleApplyReferralCode
    } = useReferrals({
      session,
      useBackend,
      refreshBalance: market.refreshBalance,
      onError: setActionError
    });
    const [apiKeyPromptOpen, setApiKeyPromptOpen] = reactExports.useState(false);
    const [deleteAccountModalOpen, setDeleteAccountModalOpen] = reactExports.useState(false);
    const [deletingAccount, setDeletingAccount] = reactExports.useState(false);
    const [deleteAccountError, setDeleteAccountError] = reactExports.useState(
      null
    );
    const [lossTurnInState, setLossTurnInState] = reactExports.useState("idle");
    const [lossTurnInError, setLossTurnInError] = reactExports.useState(null);
    const [redeemTurnInState, setRedeemTurnInState] = reactExports.useState("idle");
    const [redeemTurnInError, setRedeemTurnInError] = reactExports.useState(null);
    const [bountyTurnInState, setBountyTurnInState] = reactExports.useState("idle");
    const [bountyTurnInError, setBountyTurnInError] = reactExports.useState(null);
    const [activeInsurancePolicies, setActiveInsurancePolicies] = reactExports.useState([]);
    const [pendingInsurance, setPendingInsurance] = reactExports.useState(null);
    const [insuranceConfirmError, setInsuranceConfirmError] = reactExports.useState(null);
    const [insuranceConfirmLoading, setInsuranceConfirmLoading] = reactExports.useState(false);
    const [insuranceModalOpen, setInsuranceModalOpen] = reactExports.useState(false);
    const [insurancePerksEnabled, setInsurancePerksEnabled] = reactExports.useState(false);
    const [insuranceClaimPolicy, setInsuranceClaimPolicy] = reactExports.useState(null);
    const [activeBountyOrders, setActiveBountyOrders] = reactExports.useState([]);
    const [activeBountyContractId, setActiveBountyContractId] = reactExports.useState(null);
    const [bountyModalOpen, setBountyModalOpen] = reactExports.useState(false);
    const [pendingBounty, setPendingBounty] = reactExports.useState(
      null
    );
    const [simpleServiceModalOpen, setSimpleServiceModalOpen] = reactExports.useState(null);
    const [pendingSimpleService, setPendingSimpleService] = reactExports.useState(null);
    const [activeSimpleServices, setActiveSimpleServices] = reactExports.useState([]);
    const [activeSimpleServiceFulfillment, setActiveSimpleServiceFulfillment] = reactExports.useState(null);
    const [simpleServiceFulfillmentEndsAt, setSimpleServiceFulfillmentEndsAt] = reactExports.useState(null);
    const [simpleServiceTurnInState, setSimpleServiceTurnInState] = reactExports.useState("idle");
    const [simpleServiceTurnInError, setSimpleServiceTurnInError] = reactExports.useState(null);
    const [pendingCancelSimpleService, setPendingCancelSimpleService] = reactExports.useState(null);
    const [pendingCancelBountyOrder, setPendingCancelBountyOrder] = reactExports.useState(null);
    const [pendingBountyFulfillmentOrder, setPendingBountyFulfillmentOrder] = reactExports.useState(null);
    const activeLossContractIdRef = reactExports.useRef(market.activeLossContractId);
    activeLossContractIdRef.current = market.activeLossContractId;
    const activeRedeemingFulfillmentIdRef = reactExports.useRef(
      market.activeRedeemingFulfillmentId
    );
    activeRedeemingFulfillmentIdRef.current = market.activeRedeemingFulfillmentId;
    const activeBountyContractIdRef = reactExports.useRef(null);
    activeBountyContractIdRef.current = activeBountyContractId;
    const turnInLossIdRef = reactExports.useRef(null);
    const turnInRedeemIdRef = reactExports.useRef(null);
    const turnInBountyIdRef = reactExports.useRef(null);
    const turnInInFlightRef = reactExports.useRef(false);
    const useLiveMarket = auth2.configured;
    const payoutConversion = useXanaxMarketPrice(session, useLiveMarket);
    const logPermissionError = useTornItemReceiveLogPermission(session, useLiveMarket);
    const equipmentPermissionProbe = useTornEquipmentPermission(session, useLiveMarket);
    const showEquipmentPermissionError = equipmentPermissionProbe || equipmentPermissionError;
    reactExports.useEffect(() => {
      if (!session) {
        setEquipmentPermissionError(false);
      }
    }, [session]);
    const showFeatureBanner = payoutConversion.permissionError || logPermissionError || showEquipmentPermissionError;
    const featureBannerMessage = getFeatureReconnectApiKeyMessage({
      itemMarket: payoutConversion.permissionError,
      itemReceiveLog: logPermissionError,
      equipment: showEquipmentPermissionError
    });
    const balance = useLiveMarket ? market.balance : offlineBalance;
    const insurancePerks = useInsurancePerks(
      (session == null ? void 0 : session.torn_xid) ?? null,
      insurancePerksEnabled || insuranceModalOpen
    );
    const displayInsurancePolicies = reactExports.useMemo(
      () => activeInsurancePolicies.filter((p) => p.status === "active"),
      [activeInsurancePolicies]
    );
    const openBountyOrders = reactExports.useMemo(
      () => activeBountyOrders.filter(isVisibleBountyMarketOrder),
      [activeBountyOrders]
    );
    const bountyEscrowTotal = reactExports.useMemo(
      () => openBountyOrders.reduce((sum, o) => sum + o.escrowedTotal, 0),
      [openBountyOrders]
    );
    const bountyAvailableBalance = useLiveMarket ? balance - bountyEscrowTotal : balance;
    const simpleServiceEscrowTotal = reactExports.useMemo(
      () => activeSimpleServices.reduce((sum, s) => sum + s.escrowedPts, 0),
      [activeSimpleServices]
    );
    const simpleServiceAvailableBalance = useLiveMarket ? balance - simpleServiceEscrowTotal : balance;
    const marketListings = useLiveMarket ? market.marketListings : offlineMarketListings;
    const tornXidForDismiss = (session == null ? void 0 : session.torn_xid) ?? null;
    reactExports.useEffect(() => {
      setDismissedBuyerOrderIds(readDismissedBuyerOrderIds(tornXidForDismiss));
    }, [tornXidForDismiss]);
    reactExports.useEffect(() => {
      if (!useBackend || tornXidForDismiss == null || !market.engagementReady) return;
      const knownIds = new Set(market.buyerOrders.map((order) => order.id));
      setDismissedBuyerOrderIds(
        pruneDismissedBuyerOrderIds(tornXidForDismiss, knownIds)
      );
    }, [useBackend, tornXidForDismiss, market.buyerOrders, market.engagementReady]);
    reactExports.useEffect(() => {
      setDismissedReferencesIds(readDismissedReferencesIds(tornXidForDismiss));
    }, [tornXidForDismiss]);
    reactExports.useEffect(() => {
      setDismissedBountyRevealIds(readDismissedBountyRevealIds(tornXidForDismiss));
    }, [tornXidForDismiss]);
    const buyerOrders = reactExports.useMemo(() => {
      const source = useBackend ? market.buyerOrders : offlineBuyerOrders;
      const visible = source.filter(
        (order) => isVisibleBuyerOrder(order, dismissedBuyerOrderIds)
      );
      const byType = new Map(
        visible.map((order) => [getContractType(order), order])
      );
      return CONTRACT_TYPES.map((type) => byType.get(type)).filter(
        (order) => order != null
      );
    }, [
      useBackend,
      market.buyerOrders,
      offlineBuyerOrders,
      dismissedBuyerOrderIds
    ]);
    const redeemingListings = useLiveMarket ? market.redeemingListings : offlineRedeemingListings;
    const ownRedeemingListingIds = useBackend ? market.ownRedeemingListingIds : offlineOwnRedeemingIds;
    const offlineMyRedeemingRequest = reactExports.useMemo(() => {
      const listing = offlineRedeemingListings.find(
        (l) => offlineOwnRedeemingIds.has(l.id)
      );
      if (!listing) return null;
      return {
        id: listing.id,
        requesterId: listing.requesterId,
        quantity: listing.quantity,
        xanaxRemaining: listing.quantity,
        debitTotal: 0,
        status: "open",
        createdAt: listing.createdAt,
        completedQuantity: 0,
        activeFulfillments: []
      };
    }, [offlineRedeemingListings, offlineOwnRedeemingIds]);
    const myRedeemingRequest = useBackend ? market.myRedeemingRequest : offlineMyRedeemingRequest;
    const contractEndsAt = useBackend ? market.contractEndsAt : offlineContractEndsAt;
    const activeContract = useBackend ? market.activeContract : offlineActiveContract;
    const redeemingContractEndsAt = useBackend ? market.redeemingContractEndsAt : offlineRedeemingEndsAt;
    const activeRedeemingFulfillment = useBackend ? market.activeRedeemingFulfillment : offlineActiveRedeeming;
    const activeBountyFulfillment = offlineActiveBountyFulfillment;
    const bountyContractEndsAt = offlineBountyEndsAt;
    const [pinnedLoss, setPinnedLoss] = reactExports.useState(null);
    const [pinnedRedeem, setPinnedRedeem] = reactExports.useState(null);
    const [completedLossContract, setCompletedLossContract] = reactExports.useState(null);
    const [completedRedeemFulfillment, setCompletedRedeemFulfillment] = reactExports.useState(null);
    const [completedService, setCompletedService] = reactExports.useState(null);
    const [firstContractCompleted, setFirstContractCompleted] = reactExports.useState(false);
    reactExports.useEffect(() => {
      let cancelled = false;
      void hasFirstContractCompleted().then((seen) => {
        if (!cancelled && seen) setFirstContractCompleted(true);
      });
      return () => {
        cancelled = true;
      };
    }, []);
    const noteContractCompleted = reactExports.useCallback(() => {
      setFirstContractCompleted((prev) => {
        if (prev) return prev;
        void markFirstContractCompleted();
        return true;
      });
    }, []);
    const handleServiceCompleted = reactExports.useCallback(
      (completed) => {
        setCompletedService(completed);
        setSidebarOpen(true);
        setSettingsOpen(false);
        setMode("redeeming");
      },
      []
    );
    const handleDismissCompletedService = reactExports.useCallback(() => {
      setCompletedService(null);
    }, []);
    reactExports.useEffect(() => {
      if (activeContract && market.activeLossContractId) {
        setPinnedLoss({
          id: market.activeLossContractId,
          contract: activeContract,
          endsAtMs: contractEndsAt
        });
      } else if (!activeContract) {
        setPinnedLoss(null);
      }
    }, [activeContract, contractEndsAt, market.activeLossContractId]);
    reactExports.useEffect(() => {
      if (activeRedeemingFulfillment && market.activeRedeemingFulfillmentId) {
        setPinnedRedeem({
          id: market.activeRedeemingFulfillmentId,
          fulfillment: activeRedeemingFulfillment,
          endsAtMs: redeemingContractEndsAt
        });
      } else if (!activeRedeemingFulfillment) {
        setPinnedRedeem(null);
      }
    }, [
      activeRedeemingFulfillment,
      redeemingContractEndsAt,
      market.activeRedeemingFulfillmentId
    ]);
    reactExports.useEffect(() => {
      if (!sidebarOpen) {
        setPinnedLoss(null);
        setPinnedRedeem(null);
      }
    }, [sidebarOpen]);
    reactExports.useEffect(() => {
      if (market.activeLossContractId) {
        setCompletedLossContract(null);
      }
    }, [market.activeLossContractId]);
    reactExports.useEffect(() => {
      if (market.activeRedeemingFulfillmentId) {
        setCompletedRedeemFulfillment(null);
      }
    }, [market.activeRedeemingFulfillmentId]);
    reactExports.useEffect(() => {
      const id2 = market.activeLossContractId ?? (pinnedLoss == null ? void 0 : pinnedLoss.id) ?? null;
      if (id2) turnInLossIdRef.current = id2;
    }, [market.activeLossContractId, pinnedLoss == null ? void 0 : pinnedLoss.id]);
    reactExports.useEffect(() => {
      const id2 = market.activeRedeemingFulfillmentId ?? (pinnedRedeem == null ? void 0 : pinnedRedeem.id) ?? null;
      if (id2) turnInRedeemIdRef.current = id2;
    }, [market.activeRedeemingFulfillmentId, pinnedRedeem == null ? void 0 : pinnedRedeem.id]);
    reactExports.useEffect(() => {
      if (activeBountyContractId) {
        turnInBountyIdRef.current = activeBountyContractId;
      }
    }, [activeBountyContractId]);
    const displayLossContract = (pinnedLoss == null ? void 0 : pinnedLoss.id) === market.activeLossContractId ? pinnedLoss.contract : activeContract;
    const displayLossEndsAt = contractEndsAt;
    const displayRedeemFulfillment = (pinnedRedeem == null ? void 0 : pinnedRedeem.id) === market.activeRedeemingFulfillmentId ? pinnedRedeem.fulfillment : activeRedeemingFulfillment;
    const displayRedeemEndsAt = redeemingContractEndsAt;
    const displayBountyFulfillment = activeBountyFulfillment;
    const displayBountyEndsAt = bountyContractEndsAt;
    const currentUserXid = useBackend && session ? session.torn_xid : CURRENT_USER_XID;
    const ownBountyOrderIds = reactExports.useMemo(
      () => new Set(
        activeBountyOrders.filter((o) => o.buyerId === currentUserXid).map((o) => o.id)
      ),
      [activeBountyOrders, currentUserXid]
    );
    const runAction = reactExports.useCallback(
      async (fn, explicitSession) => {
        const activeSession = explicitSession ?? session;
        if (!activeSession) return;
        setActionError(null);
        try {
          await fn(activeSession);
          if (auth2.configured) {
            await market.refreshBalance();
            void market.refresh({ silent: true, fresh: true });
          }
        } catch (err) {
          if (isStaleBoardError(err)) {
            setActionError("That one was just taken — board updated.");
            if (auth2.configured) {
              void market.refresh({ silent: true, fresh: true });
            }
            return;
          }
          setActionError(
            err instanceof Error ? err.message : "Something went wrong"
          );
        }
      },
      [session, auth2.configured, market]
    );
    const dismissConfirmModals = reactExports.useCallback(() => {
      setPendingListing(null);
      setPendingBuyerOrder(null);
      setPendingRedeemingListing(null);
      setDepositModalOpen(false);
    }, []);
    const requireAuthOrPrompt = reactExports.useCallback(() => {
      if (!auth2.configured) return true;
      if (session) return true;
      setApiKeyPromptOpen(true);
      return false;
    }, [auth2.configured, session]);
    const {
      modalOpen: flightDelayModalOpen,
      setModalOpen: setFlightDelayModalOpen,
      pending: pendingFlightDelay,
      setPending: setPendingFlightDelay,
      active: activeFlightDelays,
      availableBalance: flightDelayAvailableBalance,
      activeFulfillment: activeFlightDelayFulfillment,
      secondsRemaining: flightDelaySecondsRemaining,
      timerActive: flightDelayTimerActive,
      showContractPanel: showFlightDelayContractPanel,
      turnInState: flightDelayTurnInState,
      turnInError: flightDelayTurnInError,
      pendingCancel: pendingCancelFlightDelay,
      open: handleOpenFlightDelay,
      proceed: handleFlightDelayContinue,
      confirmBack: handleFlightDelayConfirmBack,
      confirm: handleFlightDelayConfirm,
      take: handleTakeFlightDelay,
      turnIn: handleTurnInFlightDelay,
      requestCancel: handleRequestCancelFlightDelay,
      cancelDismiss: handleCancelFlightDelayDismiss,
      cancelConfirm: handleCancelFlightDelayConfirm
    } = useServiceOrder(
      {
        countdownSeconds: FLIGHT_DELAY_COUNTDOWN_SECONDS,
        load: loadFlightDelays,
        readStoredSync: readStoredFlightDelaysSync,
        save: saveFlightDelays,
        buildActive: (pending, createdAt) => ({
          id: crypto.randomUUID(),
          targetUserId: pending.targetUserId,
          priceTorn: pending.priceTorn,
          escrowedPts: pending.totalCostPts,
          status: "open",
          createdAt
        }),
        onCompleted: (active) => handleServiceCompleted({
          label: "Flight Delay",
          payout: active.escrowedPts,
          targetId: active.targetUserId,
          targetKind: "user"
        })
      },
      {
        tornXid: (session == null ? void 0 : session.torn_xid) ?? null,
        loadEnabled: !(useBackend && session),
        useLiveMarket,
        balance,
        setOfflineBalance,
        requireAuthOrPrompt
      }
    );
    const flightDelayContractActive = showFlightDelayContractPanel;
    const {
      modalOpen: productivityBoostModalOpen,
      setModalOpen: setProductivityBoostModalOpen,
      pending: pendingProductivityBoost,
      setPending: setPendingProductivityBoost,
      active: activeProductivityBoosts,
      availableBalance: productivityAvailableBalance,
      activeFulfillment: activeProductivityBoostFulfillment,
      secondsRemaining: productivityBoostSecondsRemaining,
      timerActive: productivityBoostTimerActive,
      showContractPanel: showProductivityBoostContractPanel,
      turnInState: productivityBoostTurnInState,
      turnInError: productivityBoostTurnInError,
      pendingCancel: pendingCancelProductivityBoost,
      open: handleOpenProductivityBoost,
      proceed: handleProductivityBoostContinue,
      confirmBack: handleProductivityBoostConfirmBack,
      confirm: handleProductivityBoostConfirm,
      take: handleTakeProductivityBoost,
      turnIn: handleTurnInProductivityBoost,
      requestCancel: handleRequestCancelProductivityBoost,
      cancelDismiss: handleCancelProductivityBoostDismiss,
      cancelConfirm: handleCancelProductivityBoostConfirm
    } = useServiceOrder(
      {
        countdownSeconds: PRODUCTIVITY_BOOST_COUNTDOWN_SECONDS,
        load: loadProductivityBoosts,
        readStoredSync: readStoredProductivityBoostsSync,
        save: saveProductivityBoosts,
        buildActive: (pending, createdAt) => ({
          id: crypto.randomUUID(),
          companyId: pending.companyId,
          priceTorn: pending.priceTorn,
          escrowedPts: pending.totalCostPts,
          status: "open",
          createdAt
        }),
        onCompleted: (active) => handleServiceCompleted({
          label: "Productivity Boost",
          payout: active.escrowedPts,
          targetId: active.companyId,
          targetKind: "company"
        })
      },
      {
        tornXid: (session == null ? void 0 : session.torn_xid) ?? null,
        loadEnabled: !(useBackend && session),
        useLiveMarket,
        balance,
        setOfflineBalance,
        requireAuthOrPrompt
      }
    );
    const productivityBoostContractActive = showProductivityBoostContractPanel;
    const enqueueAuthAction = reactExports.useCallback(
      (action) => {
        if (!auth2.configured) return;
        if (session) {
          void runAction(action, session);
          return;
        }
        dismissConfirmModals();
        setApiKeyPromptOpen(true);
      },
      [auth2.configured, session, runAction, dismissConfirmModals]
    );
    const {
      modalOpen: embargoModalOpen,
      setModalOpen: setEmbargoModalOpen,
      pending: pendingEmbargo,
      setPending: setPendingEmbargo,
      active: activeEmbargos,
      listings: embargoListings,
      availableBalance: embargoAvailableBalance,
      activeFulfillment: activeEmbargoFulfillment,
      secondsRemaining: embargoSecondsRemaining,
      timerActive: embargoTimerActive,
      showContractPanel: showEmbargoContractPanel,
      turnInState: embargoTurnInState,
      turnInError: embargoTurnInError,
      pendingCancel: pendingCancelEmbargo,
      open: handleOpenEmbargo,
      proceed: handleEmbargoContinue,
      confirmBack: handleEmbargoConfirmBack,
      confirm: handleEmbargoConfirm,
      take: handleTakeEmbargo,
      turnIn: handleTurnInEmbargo,
      requestCancel: handleRequestCancelEmbargo,
      cancelDismiss: handleCancelEmbargoDismiss,
      cancelConfirm: handleCancelEmbargoConfirm
    } = useEmbargoMarket({
      session,
      useBackend,
      balance,
      requireAuthOrPrompt,
      enqueueAuthAction,
      getApiKey: () => platform.auth.getApiKey(),
      onActivated: () => {
        setSidebarOpen(true);
        setSettingsOpen(false);
        setMode("redeeming");
      },
      onSettled: () => {
        void market.refreshBalance();
        void market.refresh({ silent: true, fresh: true });
      },
      noteContractCompleted,
      onCompleted: ({ targetUserId, payout: payout2 }) => handleServiceCompleted({
        label: "Embargo",
        payout: payout2,
        targetId: targetUserId,
        targetKind: "user"
      })
    });
    const embargoContractActive = showEmbargoContractPanel;
    const {
      modalOpen: referencesModalOpen,
      setModalOpen: setReferencesModalOpen,
      pending: pendingReferences,
      setPending: setPendingReferences,
      active: activeReferences,
      listings: referencesListings,
      availableBalance: referencesAvailableBalance,
      activeFulfillment: activeReferencesFulfillment,
      secondsRemaining: referencesSecondsRemaining,
      timerActive: referencesTimerActive,
      showContractPanel: showReferencesContractPanel,
      turnInState: referencesTurnInState,
      turnInError: referencesTurnInError,
      pendingCancel: pendingCancelReferences,
      open: handleOpenReferences,
      proceed: handleReferencesContinue,
      confirmBack: handleReferencesConfirmBack,
      confirm: handleReferencesConfirm,
      take: handleTakeReferences,
      turnIn: handleTurnInReferences,
      requestCancel: handleRequestCancelReferences,
      cancelDismiss: handleCancelReferencesDismiss,
      cancelConfirm: handleCancelReferencesConfirm
    } = useReferencesMarket({
      session,
      useBackend,
      balance,
      requireAuthOrPrompt,
      enqueueAuthAction,
      getApiKey: () => platform.auth.getApiKey(),
      onActivated: () => {
        setSidebarOpen(true);
        setSettingsOpen(false);
        setMode("redeeming");
      },
      onSettled: () => {
        void market.refreshBalance();
        void market.refresh({ silent: true, fresh: true });
      },
      noteContractCompleted,
      onCompleted: ({ targetUserId, payout: payout2 }) => handleServiceCompleted({
        label: SIMPLE_SERVICES.references.label,
        payout: payout2,
        targetId: targetUserId,
        targetKind: "user"
      })
    });
    const referencesContractActive = showReferencesContractPanel;
    const [viewReferencesReport, setViewReferencesReport] = reactExports.useState(null);
    const [archiveModalOpen, setArchiveModalOpen] = reactExports.useState(false);
    reactExports.useEffect(() => {
      if (!useBackend || tornXidForDismiss == null) return;
      const knownIds = new Set(activeReferences.map((order) => order.id));
      setDismissedReferencesIds(
        pruneDismissedReferencesIds(tornXidForDismiss, knownIds)
      );
    }, [useBackend, tornXidForDismiss, activeReferences]);
    const visibleReferences = reactExports.useMemo(
      () => activeReferences.filter((order) => !dismissedReferencesIds.has(order.id)),
      [activeReferences, dismissedReferencesIds]
    );
    const archivedReferences = reactExports.useMemo(
      () => activeReferences.filter(
        (order) => order.report != null && dismissedReferencesIds.has(order.id)
      ),
      [activeReferences, dismissedReferencesIds]
    );
    const handleArchiveReferences = reactExports.useCallback(
      (order) => {
        setDismissedReferencesIds(dismissReferences(tornXidForDismiss, order.id));
        setViewReferencesReport(null);
      },
      [tornXidForDismiss]
    );
    const handleUnarchiveReferences = reactExports.useCallback(
      (order) => {
        setDismissedReferencesIds(
          undismissReferences(tornXidForDismiss, order.id)
        );
        setViewReferencesReport(null);
      },
      [tornXidForDismiss]
    );
    const {
      modalOpen: bountyRevealModalOpen,
      setModalOpen: setBountyRevealModalOpen,
      pending: pendingBountyReveal,
      setPending: setPendingBountyReveal,
      active: activeBountyReveals,
      listings: bountyRevealListings,
      availableBalance: bountyRevealAvailableBalance,
      activeFulfillment: activeBountyRevealFulfillment,
      secondsRemaining: bountyRevealSecondsRemaining,
      timerActive: bountyRevealTimerActive,
      showContractPanel: showBountyRevealContractPanel,
      turnInState: bountyRevealTurnInState,
      turnInError: bountyRevealTurnInError,
      pendingCancel: pendingCancelBountyReveal,
      open: handleOpenBountyReveal,
      proceed: handleBountyRevealContinue,
      confirmBack: handleBountyRevealConfirmBack,
      confirm: handleBountyRevealConfirm,
      take: handleTakeBountyReveal,
      turnIn: handleTurnInBountyReveal,
      requestCancel: handleRequestCancelBountyReveal,
      cancelDismiss: handleCancelBountyRevealDismiss,
      cancelConfirm: handleCancelBountyRevealConfirm
    } = useBountyRevealMarket({
      session,
      useBackend,
      balance,
      requireAuthOrPrompt,
      enqueueAuthAction,
      getApiKey: () => platform.auth.getApiKey(),
      onActivated: () => {
        setSidebarOpen(true);
        setSettingsOpen(false);
        setMode("redeeming");
      },
      onSettled: () => {
        void market.refreshBalance();
        void market.refresh({ silent: true, fresh: true });
      },
      noteContractCompleted,
      onCompleted: ({ targetUserId, payout: payout2 }) => handleServiceCompleted({
        label: SIMPLE_SERVICES["bounty-reveal"].label,
        payout: payout2,
        targetId: targetUserId,
        targetKind: "user"
      })
    });
    const bountyRevealContractActive = showBountyRevealContractPanel;
    const [viewBountyRevealReport, setViewBountyRevealReport] = reactExports.useState(null);
    reactExports.useEffect(() => {
      if (!useBackend || tornXidForDismiss == null) return;
      const knownIds = new Set(activeBountyReveals.map((order) => order.id));
      setDismissedBountyRevealIds(
        pruneDismissedBountyRevealIds(tornXidForDismiss, knownIds)
      );
    }, [useBackend, tornXidForDismiss, activeBountyReveals]);
    const visibleBountyReveals = reactExports.useMemo(
      () => activeBountyReveals.filter(
        (order) => !dismissedBountyRevealIds.has(order.id)
      ),
      [activeBountyReveals, dismissedBountyRevealIds]
    );
    const archivedBountyReveals = reactExports.useMemo(
      () => activeBountyReveals.filter(
        (order) => order.report != null && dismissedBountyRevealIds.has(order.id)
      ),
      [activeBountyReveals, dismissedBountyRevealIds]
    );
    const handleArchiveBountyReveal = reactExports.useCallback(
      (order) => {
        setDismissedBountyRevealIds(
          dismissBountyReveal(tornXidForDismiss, order.id)
        );
        setViewBountyRevealReport(null);
      },
      [tornXidForDismiss]
    );
    const handleUnarchiveBountyReveal = reactExports.useCallback(
      (order) => {
        setDismissedBountyRevealIds(
          undismissBountyReveal(tornXidForDismiss, order.id)
        );
        setViewBountyRevealReport(null);
      },
      [tornXidForDismiss]
    );
    const handleApiKeyPromptSubmit = reactExports.useCallback(
      async (apiKey) => {
        await auth2.signIn(apiKey);
        setApiKeyPromptOpen(false);
      },
      [auth2]
    );
    const handleAddBalance = reactExports.useCallback(() => {
      if (!requireAuthOrPrompt()) return;
      setBalanceModalView("deposit");
      setDepositModalOpen(true);
    }, [requireAuthOrPrompt]);
    const handleOpenWithdraw = reactExports.useCallback(() => {
      if (!requireAuthOrPrompt()) return;
      setBalanceModalView("withdraw");
      setDepositModalOpen(true);
    }, [requireAuthOrPrompt]);
    const verifySupabase = reactExports.useMemo(
      () => useBackend && session ? getSupabase(session) : null,
      [useBackend, session]
    );
    const runVerify = reactExports.useCallback(
      async (kind, id2) => {
        if (!(session == null ? void 0 : session.access_token)) {
          return { ok: false, error: "Not signed in — reload and try again." };
        }
        let apiKey;
        try {
          apiKey = await platform.auth.getApiKey();
        } catch (err) {
          return {
            ok: false,
            error: err instanceof Error ? err.message : "Could not load API key"
          };
        }
        if (!apiKey) {
          return {
            ok: false,
            error: "API key not available — re-enter your Torn API key in Settings to verify your contract."
          };
        }
        try {
          const result = await verifyActiveFulfillment(
            session.access_token,
            kind,
            id2,
            apiKey
          );
          return {
            ok: true,
            completed: isFulfillmentCompleted(result),
            result
          };
        } catch (err) {
          const tornSuspended = err instanceof TornVerifySuspendedError;
          if (tornSuspended) {
            void platform.scheduler.scheduleContractVerify({
              kind,
              id: id2,
              endsAtMs: Date.now(),
              periodic: true
            });
          }
          return {
            ok: false,
            error: err instanceof Error ? err.message : "Verification failed",
            tornSuspended
          };
        }
      },
      [platform, session]
    );
    const captureCompletedFulfillment = reactExports.useCallback(
      (kind, outcome) => {
        if (!outcome.ok || !outcome.completed || !outcome.result) return;
        if (kind === "loss" && "contract" in outcome.result) {
          if (!isLossContractRow(outcome.result.contract)) return;
          setCompletedLossContract(lossContractToActive(outcome.result.contract));
          setPinnedLoss(null);
          turnInLossIdRef.current = null;
          noteContractCompleted();
          return;
        }
        if (kind === "redeem" && "fulfillment" in outcome.result) {
          const listing = (displayRedeemFulfillment == null ? void 0 : displayRedeemFulfillment.listing) ?? {
            id: outcome.result.fulfillment.request_id,
            requesterId: outcome.result.fulfillment.requester_xid,
            quantity: outcome.result.fulfillment.xanax_total,
            createdAt: Date.now()
          };
          setCompletedRedeemFulfillment(
            fulfillmentToActive(outcome.result.fulfillment, listing)
          );
          setPinnedRedeem(null);
          turnInRedeemIdRef.current = null;
          noteContractCompleted();
          return;
        }
        if (kind === "bounty" && "contract" in outcome.result && isBountyContractRow(outcome.result.contract)) {
          setOfflineActiveBountyFulfillment(
            bountyContractToActiveFulfillment(outcome.result.contract)
          );
          noteContractCompleted();
        }
      },
      [displayRedeemFulfillment == null ? void 0 : displayRedeemFulfillment.listing, noteContractCompleted]
    );
    const applyPollOutcome = reactExports.useCallback(
      (kind, outcome) => {
        if (!outcome.ok || !outcome.result) return;
        if (outcome.completed) {
          captureCompletedFulfillment(kind, outcome);
        } else if (kind === "loss" && "contract" in outcome.result) {
          if (!isLossContractRow(outcome.result.contract)) return;
          setPinnedLoss({
            id: outcome.result.contract.id,
            contract: lossContractToActive(outcome.result.contract),
            endsAtMs: contractEndsAt
          });
        } else if (kind === "redeem" && "fulfillment" in outcome.result) {
          const listing = (displayRedeemFulfillment == null ? void 0 : displayRedeemFulfillment.listing) ?? {
            id: outcome.result.fulfillment.request_id,
            requesterId: outcome.result.fulfillment.requester_xid,
            quantity: outcome.result.fulfillment.xanax_total,
            createdAt: Date.now()
          };
          setPinnedRedeem({
            id: outcome.result.fulfillment.id,
            fulfillment: fulfillmentToActive(outcome.result.fulfillment, listing),
            endsAtMs: redeemingContractEndsAt
          });
        } else if (kind === "bounty" && "contract" in outcome.result && isBountyContractRow(outcome.result.contract)) {
          setOfflineActiveBountyFulfillment(
            bountyContractToActiveFulfillment(outcome.result.contract)
          );
          setOfflineBountyEndsAt(new Date(outcome.result.contract.ends_at).getTime());
        }
        if (outcome.completed || isFulfillmentTerminal(outcome.result)) {
          void market.refresh({ silent: true, fresh: true });
        }
      },
      [
        contractEndsAt,
        redeemingContractEndsAt,
        displayRedeemFulfillment == null ? void 0 : displayRedeemFulfillment.listing,
        market,
        captureCompletedFulfillment
      ]
    );
    const handleDismissCompletedLoss = reactExports.useCallback(() => {
      setCompletedLossContract(null);
    }, []);
    const handleDismissCompletedRedeem = reactExports.useCallback(() => {
      setCompletedRedeemFulfillment(null);
    }, []);
    const clearContract = reactExports.useCallback(() => {
      if (useBackend) {
        void (async () => {
          const supabase2 = verifySupabase;
          const id2 = activeLossContractIdRef.current;
          if (id2) {
            void platform.scheduler.clearContractVerify("loss", id2);
            const outcome = await runVerify("loss", id2);
            if (!outcome.ok) {
              console.warn("loss contract expiry verify:", outcome.error);
              if (outcome.tornSuspended) {
                void market.refresh({ silent: true, fresh: true });
                return;
              }
            } else {
              applyPollOutcome("loss", outcome);
            }
          }
          if (supabase2) {
            try {
              await releaseMyStaleEngagements(supabase2);
            } catch (err) {
              console.warn("release stale engagements:", err);
            }
          }
          setPinnedLoss(null);
          turnInLossIdRef.current = null;
          void market.refresh({ silent: true, fresh: true });
        })();
        return;
      }
      setPinnedLoss(null);
      turnInLossIdRef.current = null;
      setOfflineContractEndsAt(null);
      setOfflineActiveContract(null);
    }, [
      useBackend,
      platform,
      market,
      runVerify,
      verifySupabase,
      applyPollOutcome
    ]);
    const clearRedeemingContract = reactExports.useCallback(() => {
      if (useBackend) {
        void (async () => {
          const supabase2 = verifySupabase;
          const id2 = activeRedeemingFulfillmentIdRef.current;
          if (id2) {
            void platform.scheduler.clearContractVerify("redeem", id2);
            const outcome = await runVerify("redeem", id2);
            if (!outcome.ok) {
              console.warn("redeem fulfillment expiry verify:", outcome.error);
              if (outcome.tornSuspended) {
                void market.refresh({ silent: true, fresh: true });
                return;
              }
            } else {
              applyPollOutcome("redeem", outcome);
            }
          }
          if (supabase2) {
            try {
              await releaseMyStaleEngagements(supabase2);
            } catch (err) {
              console.warn("release stale engagements:", err);
            }
          }
          setPinnedRedeem(null);
          turnInRedeemIdRef.current = null;
          void market.refresh({ silent: true, fresh: true });
        })();
        return;
      }
      setPinnedRedeem(null);
      turnInRedeemIdRef.current = null;
      setOfflineRedeemingEndsAt(null);
      setOfflineActiveRedeeming(null);
    }, [
      useBackend,
      platform,
      market,
      runVerify,
      verifySupabase,
      applyPollOutcome
    ]);
    const clearBountyContract = reactExports.useCallback(() => {
      if (useBackend) {
        void (async () => {
          const supabase2 = verifySupabase;
          const id2 = activeBountyContractIdRef.current;
          if (id2) {
            void platform.scheduler.clearContractVerify("bounty", id2);
            const outcome = await runVerify("bounty", id2);
            if (!outcome.ok) {
              console.warn("bounty contract expiry verify:", outcome.error);
              if (outcome.tornSuspended) {
                void market.refresh({ silent: true, fresh: true });
                return;
              }
            } else {
              applyPollOutcome("bounty", outcome);
            }
          }
          if (supabase2) {
            try {
              await releaseMyStaleEngagements(supabase2);
            } catch (err) {
              console.warn("release stale engagements:", err);
            }
          }
          setActiveBountyContractId(null);
          turnInBountyIdRef.current = null;
          setOfflineActiveBountyFulfillment(null);
          setOfflineBountyEndsAt(null);
          void market.refresh({ silent: true, fresh: true });
        })();
        return;
      }
      setOfflineBountyEndsAt(null);
      setOfflineActiveBountyFulfillment(null);
    }, [
      useBackend,
      platform,
      runVerify,
      verifySupabase,
      applyPollOutcome,
      market
    ]);
    const contractSecondsRemaining = useContractCountdown(
      displayLossEndsAt,
      clearContract
    );
    const redeemingSecondsRemaining = useContractCountdown(
      displayRedeemEndsAt,
      clearRedeemingContract
    );
    const bountySecondsRemaining = useContractCountdown(
      displayBountyEndsAt,
      clearBountyContract
    );
    const clearSimpleServiceFulfillment = reactExports.useCallback(() => {
      setActiveSimpleServiceFulfillment(null);
      setSimpleServiceFulfillmentEndsAt(null);
      setSimpleServiceTurnInState("idle");
      setSimpleServiceTurnInError(null);
    }, []);
    const simpleServiceSecondsRemaining = useContractCountdown(
      simpleServiceFulfillmentEndsAt,
      clearSimpleServiceFulfillment
    );
    const handleTakeSimpleService = reactExports.useCallback(
      (service) => {
        setActiveSimpleServiceFulfillment(service);
        setSimpleServiceFulfillmentEndsAt(
          Date.now() + SIMPLE_SERVICE_COUNTDOWN_SECONDS * 1e3
        );
        setSimpleServiceTurnInState("idle");
        setSimpleServiceTurnInError(null);
      },
      []
    );
    const handleTurnInSimpleService = reactExports.useCallback(() => {
      if (activeSimpleServiceFulfillment) {
        handleServiceCompleted({
          label: SIMPLE_SERVICES[activeSimpleServiceFulfillment.kind].label,
          payout: activeSimpleServiceFulfillment.escrowedPts,
          targetId: activeSimpleServiceFulfillment.targetUserId,
          targetKind: "user"
        });
      }
      clearSimpleServiceFulfillment();
    }, [
      activeSimpleServiceFulfillment,
      clearSimpleServiceFulfillment,
      handleServiceCompleted
    ]);
    const handleTurnInLoss = reactExports.useCallback(async () => {
      if (turnInInFlightRef.current) return;
      const id2 = turnInLossIdRef.current ?? market.activeLossContractId ?? (pinnedLoss == null ? void 0 : pinnedLoss.id) ?? null;
      if (!id2) {
        setLossTurnInError("No active contract to verify.");
        return;
      }
      turnInInFlightRef.current = true;
      setLossTurnInState("loading");
      setLossTurnInError(null);
      try {
        const outcome = await runVerify("loss", id2);
        if (!outcome.ok) {
          setLossTurnInError(outcome.error);
          setActionError(outcome.error);
          return;
        }
        applyPollOutcome("loss", outcome);
        setSidebarOpen(true);
        setSettingsOpen(false);
        setMode("buying");
        void platform.scheduler.clearContractVerify("loss", id2);
        void market.refreshBalance();
        void market.refresh({ silent: true, fresh: true });
      } finally {
        turnInInFlightRef.current = false;
        setLossTurnInState("idle");
      }
    }, [platform, market, runVerify, applyPollOutcome, pinnedLoss]);
    const handleTurnInRedeem = reactExports.useCallback(async () => {
      if (turnInInFlightRef.current) return;
      const id2 = turnInRedeemIdRef.current ?? market.activeRedeemingFulfillmentId ?? (pinnedRedeem == null ? void 0 : pinnedRedeem.id) ?? null;
      if (!id2) {
        setRedeemTurnInError("No active fulfillment to verify.");
        return;
      }
      turnInInFlightRef.current = true;
      setRedeemTurnInState("loading");
      setRedeemTurnInError(null);
      try {
        const outcome = await runVerify("redeem", id2);
        if (!outcome.ok) {
          setRedeemTurnInError(outcome.error);
          setActionError(outcome.error);
          return;
        }
        applyPollOutcome("redeem", outcome);
        setSidebarOpen(true);
        setSettingsOpen(false);
        setMode("redeeming");
        void platform.scheduler.clearContractVerify("redeem", id2);
        void market.refreshBalance();
        void market.refresh({ silent: true, fresh: true });
      } finally {
        turnInInFlightRef.current = false;
        setRedeemTurnInState("idle");
      }
    }, [platform, market, runVerify, applyPollOutcome, pinnedRedeem]);
    reactExports.useEffect(() => {
      if (!useBackend || !market.activeLossContractId || !contractEndsAt) return;
      void platform.scheduler.scheduleContractVerify({
        kind: "loss",
        id: market.activeLossContractId,
        endsAtMs: contractEndsAt
      });
    }, [platform, useBackend, market.activeLossContractId, contractEndsAt]);
    reactExports.useEffect(() => {
      if (!useBackend || !market.activeRedeemingFulfillmentId || !redeemingContractEndsAt) {
        return;
      }
      void platform.scheduler.scheduleContractVerify({
        kind: "redeem",
        id: market.activeRedeemingFulfillmentId,
        endsAtMs: redeemingContractEndsAt
      });
    }, [
      useBackend,
      platform,
      market.activeRedeemingFulfillmentId,
      redeemingContractEndsAt
    ]);
    reactExports.useEffect(() => {
      if (!useBackend || !activeBountyContractId || !bountyContractEndsAt) return;
      void platform.scheduler.scheduleContractVerify({
        kind: "bounty",
        id: activeBountyContractId,
        endsAtMs: bountyContractEndsAt
      });
    }, [useBackend, platform, activeBountyContractId, bountyContractEndsAt]);
    const lossTimerActive = displayLossEndsAt != null && contractSecondsRemaining > 0;
    const redeemTimerActive = displayRedeemEndsAt != null && redeemingSecondsRemaining > 0;
    const bountyTimerActive = displayBountyEndsAt != null && bountySecondsRemaining > 0;
    const showLossContractPanel = useBackend ? Boolean(market.activeLossContractId) && isRenderableLossContract(displayLossContract) : lossTimerActive && isRenderableLossContract(displayLossContract);
    const showRedeemContractPanel = useBackend ? Boolean(market.activeRedeemingFulfillmentId) && isRenderableRedeemFulfillment(displayRedeemFulfillment) : redeemTimerActive && isRenderableRedeemFulfillment(displayRedeemFulfillment);
    const showBountyContractPanel = bountyTimerActive && displayBountyFulfillment != null;
    const simpleServiceTimerActive = simpleServiceFulfillmentEndsAt != null && simpleServiceSecondsRemaining > 0;
    const showSimpleServiceContractPanel = simpleServiceTimerActive && activeSimpleServiceFulfillment != null;
    const simpleServiceContractActive = showSimpleServiceContractPanel;
    const showLossCompletedPanel = !showLossContractPanel && isRenderableLossContract(completedLossContract);
    const showRedeemCompletedPanel = !showRedeemContractPanel && isRenderableRedeemFulfillment(completedRedeemFulfillment);
    const contractActive = showLossContractPanel;
    const redeemingContractActive = showRedeemContractPanel;
    const bountyContractActive = showBountyContractPanel;
    const serviceContractActive = embargoContractActive || referencesContractActive || bountyRevealContractActive || productivityBoostContractActive || flightDelayContractActive || simpleServiceContractActive;
    const hasActiveFulfillment = useBackend ? Boolean(market.activeLossContractId) || Boolean(market.activeRedeemingFulfillmentId) || Boolean(activeBountyContractId) || productivityBoostTimerActive || embargoTimerActive || referencesTimerActive || bountyRevealTimerActive || flightDelayTimerActive || simpleServiceTimerActive : lossTimerActive || redeemTimerActive || bountyTimerActive || productivityBoostTimerActive || embargoTimerActive || referencesTimerActive || bountyRevealTimerActive || flightDelayTimerActive || simpleServiceTimerActive;
    const ownEmbargoListingIds = reactExports.useMemo(
      () => new Set(
        embargoListings.filter((o) => o.buyerXid === currentUserXid).map((o) => o.id)
      ),
      [embargoListings, currentUserXid]
    );
    const simpleServiceAlertEntries = reactExports.useMemo(
      () => [
        ...activeSimpleServices,
        ...referencesListings.map((order) => ({
          id: order.id,
          kind: "references",
          targetUserId: order.targetUserId,
          priceTorn: order.priceTorn,
          escrowedPts: order.escrowedPts,
          status: "open",
          createdAt: order.createdAt
        }))
      ],
      [activeSimpleServices, referencesListings]
    );
    const ownSimpleServiceAlertIds = reactExports.useMemo(
      () => new Set(
        referencesListings.filter((o) => o.buyerXid === currentUserXid).map((o) => o.id)
      ),
      [referencesListings, currentUserXid]
    );
    const ownListingIds = reactExports.useMemo(
      () => new Set(buyerOrders.filter(isOpenBuyerOrder).map((order) => order.id)),
      [buyerOrders]
    );
    const marketAlertHighlights = reactExports.useMemo(
      () => computeMarketAlertHighlights(
        marketListings,
        redeemingListings,
        {
          losses: alertThreshold,
          escapes: alertEscapeThreshold,
          stalemates: alertStalemateThreshold,
          withdrawal: alertWithdrawalThreshold,
          bounty: alertBountyThreshold,
          embargo: alertEmbargoThreshold,
          productivity: alertProductivityThreshold,
          flightDelay: alertFlightDelayThreshold,
          simpleServices: alertSimpleServiceThresholds
        },
        ownListingIds,
        ownRedeemingListingIds,
        activeBountyOrders,
        ownBountyOrderIds,
        embargoListings,
        ownEmbargoListingIds,
        activeProductivityBoosts,
        /* @__PURE__ */ new Set(),
        activeFlightDelays,
        /* @__PURE__ */ new Set(),
        simpleServiceAlertEntries,
        ownSimpleServiceAlertIds
      ),
      [
        alertThreshold,
        alertEscapeThreshold,
        alertStalemateThreshold,
        alertWithdrawalThreshold,
        alertBountyThreshold,
        alertEmbargoThreshold,
        alertProductivityThreshold,
        alertFlightDelayThreshold,
        alertSimpleServiceThresholds,
        marketListings,
        redeemingListings,
        ownListingIds,
        ownRedeemingListingIds,
        activeBountyOrders,
        ownBountyOrderIds,
        embargoListings,
        ownEmbargoListingIds,
        activeProductivityBoosts,
        activeFlightDelays,
        simpleServiceAlertEntries,
        ownSimpleServiceAlertIds
      ]
    );
    const alertMatchingKeys = marketAlertHighlights.matchingKeys;
    const alertActive = alertMatchingKeys.length > 0;
    const alertMatchSnapshotReadyRef = reactExports.useRef(false);
    const alertKeySeenRef = reactExports.useRef(/* @__PURE__ */ new Map());
    reactExports.useEffect(() => {
      alertMatchSnapshotReadyRef.current = false;
      alertKeySeenRef.current.clear();
    }, [
      session == null ? void 0 : session.torn_xid,
      alertThreshold,
      alertEscapeThreshold,
      alertStalemateThreshold,
      alertWithdrawalThreshold,
      alertBountyThreshold
    ]);
    reactExports.useEffect(() => {
      if (alertThreshold === null && alertEscapeThreshold === null && alertStalemateThreshold === null && alertWithdrawalThreshold === null && alertBountyThreshold === null) {
        return;
      }
      const needsBoardForAlerts = alertThreshold !== null || alertEscapeThreshold !== null || alertStalemateThreshold !== null || alertWithdrawalThreshold !== null;
      if (useLiveMarket && needsBoardForAlerts && !market.boardReady) return;
      const currentKeys = new Set(alertMatchingKeys);
      const now2 = Date.now();
      const seen = alertKeySeenRef.current;
      const markSeen = () => {
        for (const key of currentKeys) seen.set(key, now2);
        for (const [key, ts] of seen) {
          if (!currentKeys.has(key) && now2 - ts > ALERT_SEEN_PRUNE_TTL_MS) {
            seen.delete(key);
          }
        }
      };
      if (!alertMatchSnapshotReadyRef.current) {
        alertMatchSnapshotReadyRef.current = true;
        markSeen();
        return;
      }
      const newKeys = alertMatchingKeys.filter((key) => !seen.has(key));
      if (newKeys.length > 0) {
        void playMarketAlertSoundDeduped(newKeys, alertVolume);
      }
      markSeen();
    }, [
      alertMatchingKeys,
      alertThreshold,
      alertEscapeThreshold,
      alertStalemateThreshold,
      alertWithdrawalThreshold,
      alertBountyThreshold,
      alertVolume,
      useLiveMarket,
      market.boardReady
    ]);
    const refreshInsurancePolicies = reactExports.useCallback(
      async (activeSession) => {
        const active = activeSession ?? session;
        if (!useBackend || !active) {
          setActiveInsurancePolicies([]);
          return;
        }
        try {
          const supabase2 = getSupabase(active);
          const rows = await listMyInsurancePolicies(supabase2);
          setActiveInsurancePolicies(rows.map(mapInsurancePolicyRow));
          const renewable = rows.filter(
            (r) => r.status === "active" && r.auto_renew
          );
          if (renewable.length > 0) {
            const apiKey = await platform.auth.getApiKey();
            if (apiKey) {
              let changedAny = false;
              for (const r of renewable) {
                try {
                  const res = await refreshInsurancePolicyPerks(
                    supabase2,
                    r.id,
                    apiKey
                  );
                  if (res.changed) changedAny = true;
                } catch {
                }
              }
              if (changedAny) {
                const fresh = await listMyInsurancePolicies(supabase2);
                setActiveInsurancePolicies(fresh.map(mapInsurancePolicyRow));
              }
            }
          }
        } catch {
        }
      },
      [session, useBackend, platform]
    );
    reactExports.useEffect(() => {
      if (!useBackend || !session || !sidebarOpen) {
        if (!useBackend || !session) {
          setActiveInsurancePolicies([]);
        }
        return;
      }
      void refreshInsurancePolicies(session);
    }, [session, useBackend, sidebarOpen, refreshInsurancePolicies]);
    const refreshBountyBackend = reactExports.useCallback(
      async (activeSession) => {
        const active = activeSession ?? session;
        if (!useBackend || !active) return;
        const supabase2 = getSupabase(active);
        try {
          await releaseMyStaleEngagements(supabase2);
        } catch (err) {
          console.warn("release stale bounty engagements:", err);
        }
        const [openOrders, myProgress, activeContract2] = await Promise.all([
          fetchOpenBountyOrders(supabase2),
          fetchMyBountyOrdersProgress(supabase2),
          fetchMyActiveBountyContract(supabase2)
        ]);
        const merged = /* @__PURE__ */ new Map();
        for (const row2 of openOrders) {
          const mapped = bountyOrderRowToActive(row2);
          merged.set(mapped.id, mapped);
        }
        for (const order of bountyOrdersProgressFromJson(myProgress)) {
          merged.set(order.id, order);
        }
        setActiveBountyOrders(Array.from(merged.values()));
        if (activeContract2 == null ? void 0 : activeContract2.id) {
          setActiveBountyContractId(activeContract2.id);
          turnInBountyIdRef.current = activeContract2.id;
          setOfflineActiveBountyFulfillment(
            bountyContractToActiveFulfillment(activeContract2)
          );
          setOfflineBountyEndsAt(new Date(activeContract2.ends_at).getTime());
        } else {
          setActiveBountyContractId(null);
          turnInBountyIdRef.current = null;
          setOfflineActiveBountyFulfillment(null);
          setOfflineBountyEndsAt(null);
        }
      },
      [session, useBackend]
    );
    reactExports.useEffect(() => {
      const tornXid = (session == null ? void 0 : session.torn_xid) ?? null;
      if (useBackend && session) {
        void refreshBountyBackend(session).catch(() => {
        });
        return;
      }
      setActiveBountyContractId(null);
      setActiveBountyOrders(readStoredBountyOrdersSync(tornXid));
      void loadBountyOrders(tornXid).then(setActiveBountyOrders);
      setActiveSimpleServices(readStoredSimpleServicesSync(tornXid));
      void loadSimpleServices(tornXid).then(setActiveSimpleServices);
    }, [session == null ? void 0 : session.torn_xid, useBackend, session, refreshBountyBackend]);
    reactExports.useEffect(() => {
      if (!useBackend || !session) return;
      if (!hasExpiredActiveBountyChild(activeBountyOrders)) return;
      let cancelled = false;
      const supabase2 = getSupabase(session);
      const releaseAndRefresh = async () => {
        try {
          await releaseMyStaleEngagements(supabase2);
          if (!cancelled) {
            await refreshBountyBackend(session);
          }
        } catch (err) {
          console.warn("release stale bounty engagements:", err);
        }
      };
      void releaseAndRefresh();
      const intervalId = globalThis.setInterval(() => {
        void releaseAndRefresh();
      }, 6e4);
      return () => {
        cancelled = true;
        globalThis.clearInterval(intervalId);
      };
    }, [activeBountyOrders, useBackend, session, refreshBountyBackend]);
    const highlightedListingId = showLossContractPanel ? (displayLossContract == null ? void 0 : displayLossContract.listing.id) ?? null : null;
    const highlightedRedeemingListingId = showRedeemContractPanel ? (displayRedeemFulfillment == null ? void 0 : displayRedeemFulfillment.listing.id) ?? null : null;
    const toggleSidebar = reactExports.useCallback(() => {
      setSettingsOpen(false);
      if (market.activeLossContractId && isRenderableLossContract(activeContract) && lossTimerActive) {
        setMode("buying");
        setSidebarOpen(true);
        return;
      }
      if (market.activeRedeemingFulfillmentId && isRenderableRedeemFulfillment(activeRedeemingFulfillment) && redeemTimerActive) {
        setMode("redeeming");
        setSidebarOpen(true);
        return;
      }
      if (showBountyContractPanel || serviceContractActive) {
        setMode("redeeming");
        setSidebarOpen(true);
        return;
      }
      setSidebarOpen((open) => !open);
    }, [
      market.activeLossContractId,
      market.activeRedeemingFulfillmentId,
      activeContract,
      activeRedeemingFulfillment,
      lossTimerActive,
      redeemTimerActive,
      showBountyContractPanel,
      serviceContractActive
    ]);
    const closeSidebar = reactExports.useCallback(() => {
      setSidebarOpen(false);
    }, []);
    const panelNavTokenRef = reactExports.useRef(0);
    const [panelNav, setPanelNav] = reactExports.useState(null);
    const handleNavigateToAlert = reactExports.useCallback((target2) => {
      setSettingsOpen(false);
      setMode(target2.mode);
      setSidebarOpen(true);
      panelNavTokenRef.current += 1;
      setPanelNav({ token: panelNavTokenRef.current, target: target2 });
    }, []);
    const openSidebarForTour = reactExports.useCallback(() => {
      setSettingsOpen(false);
      setSidebarOpen(true);
    }, []);
    const insuranceTour = useInsuranceAdTourState({
      mode,
      sidebarOpen,
      onOpenSidebar: openSidebarForTour
    });
    const bountyTour = useBountyAdTourState({
      mode,
      sidebarOpen,
      onOpenSidebar: openSidebarForTour
    });
    reactExports.useEffect(() => {
      return platform.ui.onToggleSidebar(toggleSidebar);
    }, [platform, toggleSidebar]);
    const handleListingSelect = reactExports.useCallback(
      (listing) => {
        if (hasActiveFulfillment) return;
        if (ownListingIds.has(listing.id)) return;
        if (!requireAuthOrPrompt()) return;
        setPendingListing(listing);
      },
      [hasActiveFulfillment, ownListingIds, requireAuthOrPrompt]
    );
    const handleContractCancel = reactExports.useCallback(() => {
      setPendingListing(null);
    }, []);
    const handleContractConfirm = reactExports.useCallback(
      (quantity2, listing) => {
        if (hasActiveFulfillment) return;
        setPendingListing(null);
        if (auth2.configured) {
          enqueueAuthAction(async (activeSession) => {
            const supabase2 = getSupabase(activeSession);
            await acceptLossContract(supabase2, listing.id, quantity2);
          });
          return;
        }
        setOfflineActiveContract({
          listing,
          contractType: listing.contractType,
          quantity: quantity2,
          lossesRemaining: quantity2,
          lossesVerified: 0
        });
        setOfflineContractEndsAt(Date.now() + CONTRACT_COUNTDOWN_SECONDS * 1e3);
      },
      [hasActiveFulfillment, auth2.configured, enqueueAuthAction]
    );
    const handleBuyerSubmit = reactExports.useCallback(
      (contractType, payPerLoss, quantity2) => {
        if (getOpenBuyerOrderForType(buyerOrders, contractType)) return;
        if (hasActiveFulfillment) return;
        if (!requireAuthOrPrompt()) return;
        setBuyerConfirmError(null);
        setPendingBuyerOrder({ contractType, payPerLoss, quantity: quantity2 });
      },
      [buyerOrders, hasActiveFulfillment, requireAuthOrPrompt]
    );
    const handleBuyerConfirmCancel = reactExports.useCallback(() => {
      setPendingBuyerOrder(null);
      setBuyerConfirmError(null);
      setBuyerConfirmLoading(false);
    }, []);
    const handleBuyerConfirm = reactExports.useCallback(async () => {
      if (!pendingBuyerOrder || hasActiveFulfillment || buyerConfirmLoading) return;
      if (getOpenBuyerOrderForType(buyerOrders, pendingBuyerOrder.contractType)) {
        return;
      }
      const totalCost = pendingBuyerOrder.payPerLoss * pendingBuyerOrder.quantity;
      const { contractType } = pendingBuyerOrder;
      if (totalCost > balance) {
        setBuyerConfirmError("Insufficient balance for this order.");
        return;
      }
      if (auth2.configured && (contractType === "escapes" || contractType === "stalemates")) {
        setBuyerConfirmLoading(true);
        setBuyerConfirmError(null);
        try {
          const apiKey = await platform.auth.getApiKey();
          if (!apiKey) {
            setBuyerConfirmError(
              "API key not available — re-enter your Torn API key in Settings."
            );
            return;
          }
          const items = await platform.tornMarket.fetchUserEquipment();
          assertContractEquipmentFromItems(contractType, items);
        } catch (err) {
          if (isTornEquipmentPermissionError(err)) {
            setEquipmentPermissionError(true);
            return;
          }
          setBuyerConfirmError(
            err instanceof Error ? err.message : "Equipment check failed."
          );
          return;
        } finally {
          setBuyerConfirmLoading(false);
        }
      }
      if (auth2.configured) {
        enqueueAuthAction(async (activeSession) => {
          const supabase2 = getSupabase(activeSession);
          await createBuyerOrder(
            supabase2,
            pendingBuyerOrder.payPerLoss,
            pendingBuyerOrder.quantity,
            contractType
          );
          setPendingBuyerOrder(null);
          setBuyerConfirmError(null);
          setBuyerFormResetKey((k) => k + 1);
        });
        return;
      }
      const order = createBuyerOrder$1(
        currentUserXid,
        pendingBuyerOrder.payPerLoss,
        pendingBuyerOrder.quantity,
        contractType
      );
      setOfflineBalance((b) => b - totalCost);
      setOfflineBuyerOrders((prev) => upsertBuyerOrderByType(prev, order));
      setOfflineMarketListings((prev) => [
        buyerOrderToListing(order),
        ...prev.filter((l) => l.id !== order.id)
      ]);
      setPendingBuyerOrder(null);
      setBuyerConfirmError(null);
      setBuyerFormResetKey((k) => k + 1);
    }, [
      pendingBuyerOrder,
      buyerOrders,
      hasActiveFulfillment,
      buyerConfirmLoading,
      balance,
      auth2.configured,
      platform,
      enqueueAuthAction,
      currentUserXid
    ]);
    const handleOpenInsuranceModal = reactExports.useCallback(() => {
      if (!requireAuthOrPrompt()) return;
      if (!useBackend) {
        setActionError("Insurance requires signing in with your Torn API key.");
        return;
      }
      setInsurancePerksEnabled(true);
      setInsuranceModalOpen(true);
    }, [requireAuthOrPrompt, useBackend]);
    const handleOpenBountiesModal = reactExports.useCallback(() => {
      if (!requireAuthOrPrompt()) return;
      setBountyModalOpen(true);
    }, [requireAuthOrPrompt]);
    const handleOpenSimpleService = reactExports.useCallback(
      (kind) => {
        if (kind === "references") {
          handleOpenReferences();
          return;
        }
        if (kind === "bounty-reveal") {
          handleOpenBountyReveal();
          return;
        }
        if (!requireAuthOrPrompt()) return;
        setSimpleServiceModalOpen(kind);
      },
      [requireAuthOrPrompt, handleOpenReferences, handleOpenBountyReveal]
    );
    const handleSimpleServiceContinue = reactExports.useCallback(
      (order) => {
        setPendingSimpleService(order);
      },
      []
    );
    const handleSimpleServiceConfirmBack = reactExports.useCallback(() => {
      setPendingSimpleService(null);
    }, []);
    const handleSimpleServiceConfirm = reactExports.useCallback(() => {
      if (!pendingSimpleService) return;
      const targetIds = pendingSimpleService.targetUserIds;
      if (targetIds.length === 0) return;
      const grandTotal = pendingSimpleService.totalCostPts * targetIds.length;
      if (grandTotal > simpleServiceAvailableBalance) {
        return;
      }
      const createdAt = Date.now();
      const newServices = targetIds.map((targetUserId) => ({
        id: crypto.randomUUID(),
        kind: pendingSimpleService.kind,
        targetUserId,
        priceTorn: pendingSimpleService.priceTorn,
        escrowedPts: pendingSimpleService.totalCostPts,
        status: "open",
        createdAt
      }));
      const tornXid = (session == null ? void 0 : session.torn_xid) ?? null;
      setActiveSimpleServices((prev) => {
        const next = [...prev.filter((s) => s.status === "open"), ...newServices];
        void saveSimpleServices(tornXid, next);
        return next;
      });
      if (!useLiveMarket) {
        setOfflineBalance((b) => b - grandTotal);
      }
      setPendingSimpleService(null);
      setSimpleServiceModalOpen(null);
    }, [
      pendingSimpleService,
      simpleServiceAvailableBalance,
      session == null ? void 0 : session.torn_xid,
      useLiveMarket
    ]);
    const handleResolveFactionMembers = reactExports.useCallback(
      async (factionId) => {
        const apiKey = await getPlatformRuntime().auth.getApiKey();
        if (!apiKey) {
          throw new Error("Connect your Torn API key to target a faction.");
        }
        return fetchFactionMemberIds(factionId, apiKey);
      },
      []
    );
    const checkTargetStatus = reactExports.useCallback(
      async (targetId) => {
        const runtime = getPlatformRuntime();
        const apiKey = await runtime.auth.getApiKey();
        if (!apiKey) return null;
        return fetchTornTargetStatus(targetId, apiKey, runtime.fetch ?? fetch);
      },
      []
    );
    const handleRequestCancelSimpleService = reactExports.useCallback(
      (service) => {
        setPendingCancelSimpleService(service);
      },
      []
    );
    const handleCancelSimpleServiceDismiss = reactExports.useCallback(() => {
      setPendingCancelSimpleService(null);
    }, []);
    const handleCancelSimpleServiceConfirm = reactExports.useCallback(() => {
      const service = pendingCancelSimpleService;
      if (!service) return;
      const tornXid = (session == null ? void 0 : session.torn_xid) ?? null;
      setActiveSimpleServices((prev) => {
        const next = prev.filter((s) => s.id !== service.id);
        void saveSimpleServices(tornXid, next);
        return next;
      });
      if (!useLiveMarket) {
        setOfflineBalance((b) => b + service.escrowedPts);
      }
      setPendingCancelSimpleService(null);
    }, [pendingCancelSimpleService, session == null ? void 0 : session.torn_xid, useLiveMarket]);
    const handleBountyContinue = reactExports.useCallback((order) => {
      setPendingBounty(order);
    }, []);
    const handleBountyConfirmBack = reactExports.useCallback(() => {
      setPendingBounty(null);
    }, []);
    const handleBountyConfirm = reactExports.useCallback(() => {
      var _a3;
      if (!pendingBounty) return;
      if (pendingBounty.totalCostPts > bountyAvailableBalance) {
        return;
      }
      const averageXanaxPrice = ((_a3 = payoutConversion.price) == null ? void 0 : _a3.averagePrice) ?? null;
      const perContractEscrow = computeBountyOrderTotalPts(
        pendingBounty.quantity,
        pendingBounty.bountyValueTorn,
        averageXanaxPrice,
        convertTornDollarsToScriptPoints
      ).totalPts ?? pendingBounty.totalCostPts;
      if (auth2.configured) {
        enqueueAuthAction(async (activeSession) => {
          const supabase2 = getSupabase(activeSession);
          await Promise.all(
            pendingBounty.targetIds.map(
              (targetId) => createBountyOrder(
                supabase2,
                targetId,
                pendingBounty.quantity,
                pendingBounty.bountyValueTorn,
                perContractEscrow
              )
            )
          );
          await refreshBountyBackend(activeSession);
          setPendingBounty(null);
          setBountyModalOpen(false);
        });
        return;
      }
      const createdAt = Date.now();
      const newOrders = pendingBounty.targetIds.map(
        (targetId) => ({
          id: crypto.randomUUID(),
          buyerId: (session == null ? void 0 : session.torn_xid) ?? CURRENT_USER_XID,
          quantity: pendingBounty.quantity,
          quantityRemaining: pendingBounty.quantity,
          targetIds: [targetId],
          bountyValueTorn: pendingBounty.bountyValueTorn,
          escrowedTotal: perContractEscrow,
          status: "open",
          createdAt,
          activeContracts: []
        })
      );
      const tornXid = (session == null ? void 0 : session.torn_xid) ?? null;
      setActiveBountyOrders((prev) => {
        const next = [...prev.filter((o) => o.status === "open"), ...newOrders];
        void saveBountyOrders(tornXid, next);
        return next;
      });
      if (!useLiveMarket) {
        setOfflineBalance((b) => b - pendingBounty.totalCostPts);
      }
      setPendingBounty(null);
      setBountyModalOpen(false);
    }, [
      pendingBounty,
      bountyAvailableBalance,
      session == null ? void 0 : session.torn_xid,
      useLiveMarket,
      (_a2 = payoutConversion.price) == null ? void 0 : _a2.averagePrice,
      auth2.configured,
      enqueueAuthAction,
      refreshBountyBackend
    ]);
    const handleRequestCancelBountyOrder = reactExports.useCallback(
      (order) => {
        if (useBackend && session) {
          const openedOptimistically = order.activeContracts.length === 0;
          if (openedOptimistically) {
            setPendingCancelBountyOrder(order);
          }
          void (async () => {
            const supabase2 = getSupabase(session);
            try {
              await releaseMyStaleEngagements(supabase2);
              const progress2 = await fetchMyBountyOrdersProgress(supabase2);
              const fresh = bountyOrdersProgressFromJson(progress2).find(
                (candidate) => candidate.id === order.id
              );
              await refreshBountyBackend(session);
              if (((fresh == null ? void 0 : fresh.activeContracts.length) ?? 0) > 0) {
                setPendingCancelBountyOrder(
                  (current) => (current == null ? void 0 : current.id) === order.id ? null : current
                );
                setInProgressView({
                  title: "Bounty contract — in progress",
                  subtitle: "Cancellation is locked while another user is placing bounties for this order.",
                  quantityLabel: "Bounties claimed",
                  parties: (fresh == null ? void 0 : fresh.activeContracts) ?? order.activeContracts
                });
                return;
              }
              if (!openedOptimistically) {
                setPendingCancelBountyOrder(order);
              }
            } catch (err) {
              console.warn("release stale before bounty cancel:", err);
              if (!openedOptimistically) {
                setPendingCancelBountyOrder(order);
              }
            }
          })();
          return;
        }
        if (order.activeContracts.length > 0) {
          setInProgressView({
            title: "Bounty contract — in progress",
            subtitle: "Cancellation is locked while another user is placing bounties for this order.",
            quantityLabel: "Bounties claimed",
            parties: order.activeContracts
          });
          return;
        }
        setPendingCancelBountyOrder(order);
      },
      [useBackend, session, refreshBountyBackend]
    );
    const handleCancelBountyOrderConfirm = reactExports.useCallback(() => {
      if (!pendingCancelBountyOrder) return;
      const order = pendingCancelBountyOrder;
      if (useBackend && session) {
        void runAction(async (activeSession) => {
          const supabase2 = getSupabase(activeSession);
          await cancelBountyOrder(supabase2, order.id);
          await refreshBountyBackend(activeSession);
        });
        setPendingCancelBountyOrder(null);
        return;
      }
      const refundAmount = getBountyOrderRefundAmount(order);
      const tornXid = (session == null ? void 0 : session.torn_xid) ?? null;
      setActiveBountyOrders((prev) => {
        const next = prev.filter((o) => o.id !== order.id);
        void saveBountyOrders(tornXid, next);
        return next;
      });
      if (!useLiveMarket) {
        setOfflineBalance((b) => b + refundAmount);
      }
      setPendingCancelBountyOrder(null);
    }, [
      pendingCancelBountyOrder,
      session == null ? void 0 : session.torn_xid,
      useLiveMarket,
      useBackend,
      session,
      runAction,
      refreshBountyBackend
    ]);
    const handleCancelBountyOrderDismiss = reactExports.useCallback(() => {
      setPendingCancelBountyOrder(null);
    }, []);
    const handlePurchaseInsurance = reactExports.useCallback(
      (purchase) => {
        if (displayInsurancePolicies.some((p) => p.planId === purchase.planId)) {
          return;
        }
        setInsuranceConfirmError(null);
        setPendingInsurance(purchase);
      },
      [displayInsurancePolicies]
    );
    const handleInsuranceConfirmCancel = reactExports.useCallback(() => {
      setPendingInsurance(null);
      setInsuranceConfirmError(null);
      setInsuranceConfirmLoading(false);
    }, []);
    const handleInsuranceConfirm = reactExports.useCallback(async () => {
      if (!pendingInsurance || insuranceConfirmLoading) return;
      if (displayInsurancePolicies.some(
        (p) => p.planId === pendingInsurance.planId
      )) {
        setInsuranceConfirmError(
          "You already have an active policy for this plan."
        );
        return;
      }
      if (pendingInsurance.coverage > balance) {
        setInsuranceConfirmError("Insufficient balance for this policy.");
        return;
      }
      if (!session) {
        setApiKeyPromptOpen(true);
        return;
      }
      const apiKey = await platform.auth.getApiKey();
      if (!apiKey) {
        setInsuranceConfirmError(
          "API key not available — re-enter your Torn API key in Settings."
        );
        return;
      }
      setInsuranceConfirmLoading(true);
      setInsuranceConfirmError(null);
      try {
        const result = await purchaseInsurancePolicy(session.access_token, {
          plan_id: pendingInsurance.planId,
          premium: pendingInsurance.coverage,
          effective_multiplier: pendingInsurance.effectiveMultiplier,
          payout: pendingInsurance.payout,
          auto_renew: pendingInsurance.autoRenew,
          api_key: apiKey
        });
        setActiveInsurancePolicies((prev) => {
          const mapped = mapInsurancePolicyRow(result.policy);
          const without = prev.filter((p) => p.id !== mapped.id);
          return [...without, mapped];
        });
        if (auth2.configured) {
          await market.refreshBalance();
          void market.refresh({ silent: true, fresh: true });
        }
        setPendingInsurance(null);
        setInsuranceModalOpen(false);
      } catch (err) {
        const message = err instanceof Error ? err.message : "Purchase failed.";
        if (typeof err === "object" && err !== null && "server_multiplier" in err) {
          void insurancePerks.refresh();
          setInsuranceConfirmError(
            `${message} Multipliers were refreshed — review your plan and try again.`
          );
        } else {
          setInsuranceConfirmError(message);
        }
      } finally {
        setInsuranceConfirmLoading(false);
      }
    }, [
      pendingInsurance,
      insuranceConfirmLoading,
      displayInsurancePolicies,
      balance,
      session,
      platform,
      auth2.configured,
      market,
      insurancePerks
    ]);
    const handleInsuranceExpired = reactExports.useCallback(
      (_policyId) => {
        void refreshInsurancePolicies();
      },
      [refreshInsurancePolicies]
    );
    const handleInsuranceClaimSuccess = reactExports.useCallback(
      (updated) => {
        setActiveInsurancePolicies(
          (prev) => prev.map((p) => p.id === updated.id ? updated : p)
        );
        if (auth2.configured) {
          void market.refreshBalance();
          void market.refresh({ silent: true, fresh: true });
        }
      },
      [auth2.configured, market]
    );
    const handleSetInsuranceAutoRenew = reactExports.useCallback(
      async (policyId, autoRenew) => {
        if (!session) {
          throw new Error("Sign in to manage auto-renew.");
        }
        const row2 = await setMyInsuranceAutoRenew(
          getSupabase(session),
          policyId,
          autoRenew
        );
        const updated = mapInsurancePolicyRow(row2);
        setActiveInsurancePolicies(
          (prev) => prev.map((p) => p.id === policyId ? updated : p)
        );
        setInsuranceClaimPolicy(
          (prev) => (prev == null ? void 0 : prev.id) === policyId ? updated : prev
        );
      },
      [session]
    );
    const handleDismissCompletedBuyerOrder = reactExports.useCallback(
      (order) => {
        const tornXid = (session == null ? void 0 : session.torn_xid) ?? null;
        setDismissedBuyerOrderIds(dismissBuyerOrder(tornXid, order.id));
      },
      [session == null ? void 0 : session.torn_xid]
    );
    const handleRequestCancelBuyerOrder = reactExports.useCallback(
      (order) => {
        const orderType = getContractType(order);
        const orderLabel = CONTRACT_TYPE_LABELS[orderType];
        if (order.activeContracts.length > 0) {
          setInProgressView({
            title: `${orderLabel} contract — in progress`,
            subtitle: `Cancellation is locked while another user is delivering ${orderLabel.toLowerCase()} for this contract.`,
            quantityLabel: `${orderLabel} claimed`,
            parties: order.activeContracts,
            pausableOrder: { id: order.id, isPaused: order.isPaused }
          });
          return;
        }
        setPendingCancelBuyerOrder(order);
      },
      []
    );
    const handleRequestCancelBuyerOrderByListing = reactExports.useCallback(
      (listingId) => {
        const order = buyerOrders.find((candidate) => candidate.id === listingId);
        if (!order) return;
        handleRequestCancelBuyerOrder(order);
      },
      [buyerOrders, handleRequestCancelBuyerOrder]
    );
    const handleToggleBuyerOrderPause = reactExports.useCallback(
      (orderId, currentPaused) => {
        const next = !currentPaused;
        setBuyerOrderProgressView(
          (prev) => prev && prev.id === orderId ? { ...prev, isPaused: next } : prev
        );
        setInProgressView(
          (prev) => {
            var _a3;
            return prev && ((_a3 = prev.pausableOrder) == null ? void 0 : _a3.id) === orderId ? { ...prev, pausableOrder: { id: orderId, isPaused: next } } : prev;
          }
        );
        const isBackendOrder = useBackend && !!session && market.buyerOrders.some((o) => o.id === orderId);
        if (isBackendOrder && session) {
          const activeSession = session;
          void (async () => {
            try {
              await setBuyerOrderPaused(
                getSupabase(activeSession),
                orderId,
                next
              );
              void market.refresh({ silent: true, fresh: true });
            } catch (err) {
              setBuyerOrderProgressView(
                (prev) => prev && prev.id === orderId ? { ...prev, isPaused: currentPaused } : prev
              );
              setInProgressView(
                (prev) => {
                  var _a3;
                  return prev && ((_a3 = prev.pausableOrder) == null ? void 0 : _a3.id) === orderId ? {
                    ...prev,
                    pausableOrder: { id: orderId, isPaused: currentPaused }
                  } : prev;
                }
              );
              setActionError(
                err instanceof Error ? err.message : "Failed to update pause state"
              );
            }
          })();
          return;
        }
        setOfflineBuyerOrders(
          (prev) => prev.map((o) => o.id === orderId ? { ...o, isPaused: next } : o)
        );
      },
      [useBackend, session, market]
    );
    const handleCancelBuyerOrderDismiss = reactExports.useCallback(() => {
      setPendingCancelBuyerOrder(null);
    }, []);
    const handleCancelBuyerOrderConfirm = reactExports.useCallback(() => {
      if (!pendingCancelBuyerOrder) return;
      const order = pendingCancelBuyerOrder;
      const isBackendOrder = useBackend && session && market.buyerOrders.some((o) => o.id === order.id);
      if (isBackendOrder) {
        const orderId = order.id;
        market.clearBuyerOrder();
        market.removeBoardListing(orderId);
        setPendingCancelBuyerOrder(null);
        void runAction(async (activeSession) => {
          const supabase2 = getSupabase(activeSession);
          try {
            await cancelBuyerOrder(supabase2, orderId);
          } catch (err) {
            const msg = err instanceof Error ? err.message : "";
            if (!msg.includes("order not found") && !msg.includes("order is not open")) {
              throw err;
            }
          }
        });
        return;
      }
      const refund = getBuyerOrderRefund(order);
      setOfflineBalance((b) => b + refund);
      setOfflineBuyerOrders(
        (prev) => prev.filter((candidate) => candidate.id !== order.id)
      );
      setOfflineMarketListings(
        (prev) => prev.filter((listing) => listing.id !== order.id)
      );
      setPendingCancelBuyerOrder(null);
    }, [
      pendingCancelBuyerOrder,
      useBackend,
      session,
      runAction,
      market
    ]);
    const handleWithdraw = reactExports.useCallback(
      (xanaxCount) => {
        const total = getWithdrawTotalDebit(xanaxCount);
        if (total > balance) return;
        if (auth2.configured) {
          enqueueAuthAction(async (activeSession) => {
            const supabase2 = getSupabase(activeSession);
            await createRedeemingRequest(supabase2, xanaxCount);
            setDepositModalOpen(false);
          });
          return;
        }
        const listing = createRedeemingListing(xanaxCount);
        setOfflineBalance((b) => b - total);
        setOfflineRedeemingListings((prev) => [listing, ...prev]);
        setOfflineOwnRedeemingIds((prev) => new Set(prev).add(listing.id));
      },
      [balance, auth2.configured, enqueueAuthAction]
    );
    const handleRedeemingListingSelect = reactExports.useCallback(
      (listing) => {
        if (hasActiveFulfillment) return;
        if (ownRedeemingListingIds.has(listing.id)) return;
        if (!requireAuthOrPrompt()) return;
        setPendingRedeemingListing(listing);
      },
      [hasActiveFulfillment, ownRedeemingListingIds, requireAuthOrPrompt]
    );
    const handleBountyOrderSelect = reactExports.useCallback(
      (order) => {
        if (hasActiveFulfillment) return;
        if (order.targetIds[0] == null) return;
        setPendingBountyFulfillmentOrder(order);
      },
      [hasActiveFulfillment]
    );
    const handleBountyFulfillCancel = reactExports.useCallback(() => {
      setPendingBountyFulfillmentOrder(null);
    }, []);
    const handleBountyFulfillConfirm = reactExports.useCallback(
      (quantity2, order) => {
        if (hasActiveFulfillment) return;
        const targetId = order.targetIds[0];
        if (targetId == null) return;
        setPendingBountyFulfillmentOrder(null);
        if (auth2.configured) {
          enqueueAuthAction(async (activeSession) => {
            const supabase2 = getSupabase(activeSession);
            const contract = await acceptBountyContract(
              supabase2,
              order.id,
              quantity2
            );
            setActiveBountyContractId(contract.id);
            turnInBountyIdRef.current = contract.id;
            setOfflineActiveBountyFulfillment(
              bountyContractToActiveFulfillment(contract)
            );
            setOfflineBountyEndsAt(new Date(contract.ends_at).getTime());
            await refreshBountyBackend(activeSession);
            setSidebarOpen(true);
            setSettingsOpen(false);
            setMode("redeeming");
          });
          return;
        }
        setOfflineActiveBountyFulfillment({
          order,
          targetId,
          slotsTotal: quantity2,
          slotsRemaining: quantity2,
          slotsVerified: 0
        });
        setOfflineBountyEndsAt(
          Date.now() + BOUNTY_COUNTDOWN_SECONDS * 1e3
        );
        setSidebarOpen(true);
        setSettingsOpen(false);
        setMode("redeeming");
      },
      [hasActiveFulfillment, auth2.configured, enqueueAuthAction, refreshBountyBackend]
    );
    const handleTurnInBounty = reactExports.useCallback(async () => {
      if (turnInInFlightRef.current) return;
      const id2 = turnInBountyIdRef.current ?? activeBountyContractIdRef.current;
      if (!id2) {
        setBountyTurnInError("No active bounty contract to verify.");
        return;
      }
      turnInInFlightRef.current = true;
      setBountyTurnInState("loading");
      setBountyTurnInError(null);
      try {
        const outcome = await runVerify("bounty", id2);
        if (!outcome.ok) {
          setBountyTurnInError(outcome.error);
          setActionError(outcome.error);
          return;
        }
        if (outcome.result && "contract" in outcome.result && isBountyContractRow(outcome.result.contract)) {
          setOfflineActiveBountyFulfillment(
            bountyContractToActiveFulfillment(outcome.result.contract)
          );
        }
        if (outcome.completed || outcome.result && isFulfillmentTerminal(outcome.result)) {
          setOfflineActiveBountyFulfillment(null);
          setOfflineBountyEndsAt(null);
          setActiveBountyContractId(null);
          turnInBountyIdRef.current = null;
          void platform.scheduler.clearContractVerify("bounty", id2);
          if (session) {
            void refreshBountyBackend(session);
          }
          void market.refreshBalance();
          void market.refresh({ silent: true, fresh: true });
          if (outcome.completed) noteContractCompleted();
        }
      } finally {
        turnInInFlightRef.current = false;
        setBountyTurnInState("idle");
      }
    }, [platform, market, session, runVerify, refreshBountyBackend, noteContractCompleted]);
    const handleRedeemingFulfillCancel = reactExports.useCallback(() => {
      setPendingRedeemingListing(null);
    }, []);
    const handleRedeemingFulfillConfirm = reactExports.useCallback(
      (quantity2, listing) => {
        if (hasActiveFulfillment) return;
        setPendingRedeemingListing(null);
        if (auth2.configured) {
          enqueueAuthAction(async (activeSession) => {
            const supabase2 = getSupabase(activeSession);
            await acceptRedeemingFulfillment(
              supabase2,
              listing.id,
              quantity2
            );
          });
          return;
        }
        setOfflineActiveRedeeming({
          listing,
          xanaxTotal: quantity2,
          xanaxRemaining: quantity2,
          xanaxVerified: 0
        });
        setOfflineRedeemingEndsAt(
          Date.now() + REDEEMING_COUNTDOWN_SECONDS * 1e3
        );
      },
      [hasActiveFulfillment, auth2.configured, enqueueAuthAction]
    );
    const showRedeemingInProgressModal = reactExports.useCallback(
      (request) => {
        setInProgressView({
          title: "Withdrawal — in progress",
          subtitle: "Cancellation is locked while another user is fulfilling part of this request.",
          quantityLabel: "Xanax claimed",
          parties: request.activeFulfillments
        });
      },
      []
    );
    const handleRequestCancelRedeeming = reactExports.useCallback(
      (listing) => {
        if (!ownRedeemingListingIds.has(listing.id)) return;
        if ((myRedeemingRequest == null ? void 0 : myRedeemingRequest.id) === listing.id && myRedeemingRequest.activeFulfillments.length > 0) {
          showRedeemingInProgressModal(myRedeemingRequest);
          return;
        }
        setPendingCancelRedeeming(listing);
      },
      [ownRedeemingListingIds, myRedeemingRequest, showRedeemingInProgressModal]
    );
    const handleRequestCancelMyRedeeming = reactExports.useCallback(
      (request) => {
        if (request.activeFulfillments.length > 0) {
          showRedeemingInProgressModal(request);
          return;
        }
        setPendingCancelRedeeming({
          id: request.id,
          requesterId: request.requesterId,
          quantity: request.xanaxRemaining,
          createdAt: request.createdAt
        });
      },
      [showRedeemingInProgressModal]
    );
    const handleCancelRedeemingDismiss = reactExports.useCallback(() => {
      setPendingCancelRedeeming(null);
    }, []);
    const handleCancelRedeemingConfirm = reactExports.useCallback(() => {
      if (!pendingCancelRedeeming) return;
      if (useBackend && session) {
        market.removeBoardListing(pendingCancelRedeeming.id);
        void runAction(async (activeSession) => {
          const supabase2 = getSupabase(activeSession);
          await cancelRedeemingRequest(
            supabase2,
            pendingCancelRedeeming.id
          );
          setPendingCancelRedeeming(null);
        });
        return;
      }
      const refund = getWithdrawTotalDebit(pendingCancelRedeeming.quantity);
      setOfflineBalance((b) => b + refund);
      setOfflineRedeemingListings(
        (prev) => prev.filter((l) => l.id !== pendingCancelRedeeming.id)
      );
      setOfflineOwnRedeemingIds((prev) => {
        const next = new Set(prev);
        next.delete(pendingCancelRedeeming.id);
        return next;
      });
      setPendingCancelRedeeming(null);
    }, [pendingCancelRedeeming, useBackend, session, runAction, market]);
    return /* @__PURE__ */ jsxRuntimeExports.jsx(InsuranceAdTourProvider, { value: insuranceTour, children: /* @__PURE__ */ jsxRuntimeExports.jsx(BountyAdTourProvider, { value: bountyTour, children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles.root, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(OdInsuranceAd, { onActivate: insuranceTour.startTour }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        BountyPlacementAutofill,
        {
          contract: displayBountyFulfillment ? {
            targetId: displayBountyFulfillment.targetId,
            rewardPerHosp: displayBountyFulfillment.order.bountyValueTorn,
            quantityNeeded: displayBountyFulfillment.slotsRemaining || displayBountyFulfillment.slotsTotal
          } : null,
          onOpenPanel: bountyTour.startTour
        }
      ),
      showRedeemContractPanel && displayRedeemFulfillment ? /* @__PURE__ */ jsxRuntimeExports.jsx(
        ItemSendAutofill,
        {
          recipientId: displayRedeemFulfillment.listing.requesterId,
          amount: Math.min(
            displayRedeemFulfillment.xanaxRemaining ?? Math.max(
              0,
              (displayRedeemFulfillment.xanaxTotal ?? 0) - (displayRedeemFulfillment.xanaxVerified ?? 0)
            ),
            displayRedeemFulfillment.xanaxTotal ?? 0
          )
        }
      ) : null,
      showFeatureBanner ? /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: styles.bannerFeature, role: "status", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: featureBannerMessage }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "button",
          {
            type: "button",
            className: styles.bannerFeatureButton,
            onClick: () => {
              void auth2.signOut();
              window.open(CREATE_API_KEY_URL, "_blank", "noopener,noreferrer");
              setApiKeyPromptOpen(true);
            },
            children: "Sign Out"
          }
        )
      ] }) : market.error ?? actionError ? /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: styles.banner, role: "alert", children: market.error ?? actionError }) : null,
      !isWebPlatform() ? /* @__PURE__ */ jsxRuntimeExports.jsx(
        MarketPanelButton,
        {
          onClick: toggleSidebar,
          sidebarOpen,
          alertActive,
          contractActive,
          contractSecondsRemaining,
          redeemingContractActive,
          redeemingSecondsRemaining,
          bountyContractActive,
          bountySecondsRemaining,
          productivityBoostContractActive,
          productivityBoostSecondsRemaining,
          embargoContractActive,
          embargoSecondsRemaining,
          flightDelayContractActive,
          flightDelaySecondsRemaining,
          simpleServiceContractActive: simpleServiceContractActive || referencesContractActive,
          simpleServiceSecondsRemaining: simpleServiceContractActive ? simpleServiceSecondsRemaining : referencesSecondsRemaining
        }
      ) : null,
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Sidebar,
        {
          open: sidebarOpen,
          allowClose: !isWebPlatform(),
          mode,
          firstContractCompleted,
          onModeChange: (next) => {
            setSettingsOpen(false);
            setMode(next);
          },
          onClose: closeSidebar,
          settingsOpen,
          onSettingsToggle: () => setSettingsOpen((open) => !open),
          onOpenSettings: () => setSettingsOpen(true),
          alerts: alertSettings,
          modeAlertHighlights: {
            buying: marketAlertHighlights.sellModeAlert,
            redeeming: marketAlertHighlights.redeemingModeAlert
          },
          contractTypeAlertHighlights: marketAlertHighlights.contractTypeAlerts,
          withdrawalAlertActive: marketAlertHighlights.withdrawalAlertActive,
          bountyAlertActive: marketAlertHighlights.bountyAlertActive,
          embargoAlertActive: marketAlertHighlights.embargoAlertActive,
          productivityAlertActive: marketAlertHighlights.productivityAlertActive,
          flightDelayAlertActive: marketAlertHighlights.flightDelayAlertActive,
          simpleServiceAlertActive: marketAlertHighlights.simpleServiceAlertActive,
          onNavigateToAlert: handleNavigateToAlert,
          panelNav,
          matchingAlertCount: alertMatchingKeys.length,
          matchingAlertCounts: marketAlertHighlights.matchingCounts,
          alertingOtherSubtypes: marketAlertHighlights.alertingOtherSubtypes,
          session,
          onLogout: async () => {
            await auth2.signOut();
            setSettingsOpen(false);
          },
          ...{
            onRequestDeleteAccount: () => {
              setDeleteAccountError(null);
              setDeleteAccountModalOpen(true);
            },
            deletingAccount
          },
          onConnectApiKey: () => setApiKeyPromptOpen(true),
          onOpenReferrals: useBackend && session ? handleOpenReferrals : void 0,
          onViewArchive: useBackend && session ? () => setArchiveModalOpen(true) : void 0,
          archiveCount: archivedReferences.length + archivedBountyReveals.length,
          balance,
          onListingSelect: handleListingSelect,
          onCancelOwnListing: handleRequestCancelBuyerOrderByListing,
          showLossContractPanel,
          showLossCompletedPanel,
          displayLossContract,
          completedLossContract,
          contractSecondsRemaining,
          onDismissCompletedLoss: handleDismissCompletedLoss,
          showRedeemContractPanel,
          showRedeemCompletedPanel,
          displayRedeemFulfillment,
          completedRedeemFulfillment,
          onDismissCompletedRedeem: handleDismissCompletedRedeem,
          completedService,
          onDismissCompletedService: handleDismissCompletedService,
          contractActive,
          marketListings,
          buyerOrders,
          hasActiveFulfillment,
          highlightedListingId,
          ownListingIds,
          onBuyerSubmit: handleBuyerSubmit,
          onCancelBuyerOrder: handleRequestCancelBuyerOrder,
          onShowInProgressView: setInProgressView,
          onShowBuyerOrderProgress: setBuyerOrderProgressView,
          onDismissCompletedBuyerOrder: handleDismissCompletedBuyerOrder,
          buyerFormResetKey,
          onBalanceClick: () => {
            setBalanceModalView(balance > 0 ? "withdraw" : "deposit");
            setDepositModalOpen(true);
          },
          onAddBalance: handleAddBalance,
          redeemingListings,
          ownRedeemingListingIds,
          myRedeemingRequest,
          onRedeemingListingSelect: handleRedeemingListingSelect,
          onCancelRedeemingRequest: handleRequestCancelRedeeming,
          onCancelMyRedeemingRequest: handleRequestCancelMyRedeeming,
          redeemingContractActive,
          redeemingSecondsRemaining,
          highlightedRedeemingListingId,
          currentUserXid,
          balanceLoading: useLiveMarket && (auth2.loading || session !== null && !market.engagementReady || sidebarOpen && market.boardLoading),
          boardLoading: useLiveMarket && sidebarOpen && market.boardLoading,
          sessionLoading: auth2.loading,
          onTurnInLossContract: () => void handleTurnInLoss(),
          lossTurnInState,
          lossTurnInError,
          onTurnInRedeemFulfillment: () => void handleTurnInRedeem(),
          redeemTurnInState,
          redeemTurnInError,
          payoutConversion,
          activeInsurancePolicies: displayInsurancePolicies,
          onInsuranceExpired: handleInsuranceExpired,
          onOpenInsuranceModal: handleOpenInsuranceModal,
          onFileInsuranceClaim: setInsuranceClaimPolicy,
          onDisableInsuranceAutoRenew: (policyId) => handleSetInsuranceAutoRenew(policyId, false),
          activeBountyOrders: openBountyOrders,
          onOpenBountiesModal: handleOpenBountiesModal,
          onCancelBountyOrder: handleRequestCancelBountyOrder,
          onOpenWithdraw: handleOpenWithdraw,
          onOpenProductivityBoost: handleOpenProductivityBoost,
          activeProductivityBoosts,
          onCancelProductivityBoost: handleRequestCancelProductivityBoost,
          onBountyOrderSelect: handleBountyOrderSelect,
          showBountyContractPanel,
          displayBountyFulfillment,
          bountySecondsRemaining,
          bountyContractActive,
          serviceContractActive,
          onTurnInBountyFulfillment: handleTurnInBounty,
          bountyTurnInState,
          bountyTurnInError,
          onTakeProductivityBoost: handleTakeProductivityBoost,
          showProductivityBoostContractPanel,
          activeProductivityBoostFulfillment,
          productivityBoostSecondsRemaining,
          onTurnInProductivityBoost: handleTurnInProductivityBoost,
          productivityBoostTurnInState,
          productivityBoostTurnInError,
          onOpenEmbargo: handleOpenEmbargo,
          activeEmbargos,
          embargoListings,
          onCancelEmbargo: handleRequestCancelEmbargo,
          onTakeEmbargo: handleTakeEmbargo,
          showEmbargoContractPanel,
          activeEmbargoFulfillment,
          embargoSecondsRemaining,
          onTurnInEmbargo: handleTurnInEmbargo,
          embargoTurnInState,
          embargoTurnInError,
          activeReferences: visibleReferences,
          referencesListings,
          onCancelReferences: handleRequestCancelReferences,
          onTakeReferences: handleTakeReferences,
          showReferencesContractPanel,
          activeReferencesFulfillment,
          referencesSecondsRemaining,
          onTurnInReferences: handleTurnInReferences,
          referencesTurnInState,
          referencesTurnInError,
          onViewReferencesReport: setViewReferencesReport,
          activeBountyReveals: visibleBountyReveals,
          bountyRevealListings,
          onCancelBountyReveal: handleRequestCancelBountyReveal,
          onTakeBountyReveal: handleTakeBountyReveal,
          showBountyRevealContractPanel,
          activeBountyRevealFulfillment,
          bountyRevealSecondsRemaining,
          onTurnInBountyReveal: handleTurnInBountyReveal,
          bountyRevealTurnInState,
          bountyRevealTurnInError,
          onViewBountyRevealReport: setViewBountyRevealReport,
          onOpenFlightDelay: handleOpenFlightDelay,
          activeFlightDelays,
          onCancelFlightDelay: handleRequestCancelFlightDelay,
          onTakeFlightDelay: handleTakeFlightDelay,
          showFlightDelayContractPanel,
          activeFlightDelayFulfillment,
          flightDelaySecondsRemaining,
          onTurnInFlightDelay: handleTurnInFlightDelay,
          flightDelayTurnInState,
          flightDelayTurnInError,
          onOpenSimpleService: handleOpenSimpleService,
          activeSimpleServices,
          onCancelSimpleService: handleRequestCancelSimpleService,
          onTakeSimpleService: handleTakeSimpleService,
          showSimpleServiceContractPanel,
          activeSimpleServiceFulfillment,
          simpleServiceSecondsRemaining,
          onTurnInSimpleService: handleTurnInSimpleService,
          simpleServiceTurnInState,
          simpleServiceTurnInError
        }
      ),
      insuranceClaimPolicy && session && /* @__PURE__ */ jsxRuntimeExports.jsx(
        InsuranceClaimModal,
        {
          policy: insuranceClaimPolicy,
          accessToken: session.access_token,
          payoutConversion,
          onClose: () => setInsuranceClaimPolicy(null),
          onExpired: handleInsuranceExpired,
          onClaimSuccess: handleInsuranceClaimSuccess,
          onSetAutoRenew: handleSetInsuranceAutoRenew
        }
      ),
      pendingListing && !hasActiveFulfillment && /* @__PURE__ */ jsxRuntimeExports.jsx(
        ContractModal,
        {
          listing: pendingListing,
          onConfirm: handleContractConfirm,
          onCancel: handleContractCancel,
          payoutConversion,
          checkTargetStatus
        }
      ),
      pendingBuyerOrder && /* @__PURE__ */ jsxRuntimeExports.jsx(
        BuyerOrderConfirmModal,
        {
          order: pendingBuyerOrder,
          balance,
          error: buyerConfirmError,
          confirming: buyerConfirmLoading,
          onConfirm: () => void handleBuyerConfirm(),
          onCancel: handleBuyerConfirmCancel,
          onAddBalance: handleAddBalance,
          payoutConversion
        }
      ),
      insuranceModalOpen && /* @__PURE__ */ jsxRuntimeExports.jsx(
        InsurancePolicyModal,
        {
          open: insuranceModalOpen,
          activePolicies: displayInsurancePolicies,
          availableBalance: balance,
          tornXid: (session == null ? void 0 : session.torn_xid) ?? null,
          effectiveMultipliers: insurancePerks.effectiveMultipliers,
          perksLoading: insurancePerks.loading,
          perksError: insurancePerks.error,
          onPurchase: handlePurchaseInsurance,
          onClose: () => {
            setInsuranceModalOpen(false);
          },
          onAddBalance: handleAddBalance
        }
      ),
      pendingInsurance && /* @__PURE__ */ jsxRuntimeExports.jsx(
        InsuranceConfirmModal,
        {
          purchase: pendingInsurance,
          balance,
          error: insuranceConfirmError,
          confirming: insuranceConfirmLoading,
          onConfirm: () => void handleInsuranceConfirm(),
          onBack: handleInsuranceConfirmCancel,
          onAddBalance: handleAddBalance
        }
      ),
      bountyModalOpen && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          BountyOrderModal,
          {
            onContinue: handleBountyContinue,
            onCancel: () => {
              setBountyModalOpen(false);
              setPendingBounty(null);
            },
            payoutConversion,
            balance: bountyAvailableBalance
          }
        ),
        pendingBounty && /* @__PURE__ */ jsxRuntimeExports.jsx(
          BountyConfirmModal,
          {
            order: pendingBounty,
            balance: bountyAvailableBalance,
            payoutConversion,
            onConfirm: handleBountyConfirm,
            onBack: handleBountyConfirmBack,
            onAddBalance: handleAddBalance
          }
        )
      ] }),
      productivityBoostModalOpen && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          ProductivityBoostOrderModal,
          {
            onContinue: handleProductivityBoostContinue,
            onCancel: () => {
              setProductivityBoostModalOpen(false);
              setPendingProductivityBoost(null);
            },
            payoutConversion,
            balance: productivityAvailableBalance
          }
        ),
        pendingProductivityBoost && /* @__PURE__ */ jsxRuntimeExports.jsx(
          ProductivityBoostConfirmModal,
          {
            order: pendingProductivityBoost,
            balance: productivityAvailableBalance,
            payoutConversion,
            onConfirm: handleProductivityBoostConfirm,
            onBack: handleProductivityBoostConfirmBack,
            onAddBalance: handleAddBalance
          }
        )
      ] }),
      embargoModalOpen && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          EmbargoOrderModal,
          {
            onContinue: handleEmbargoContinue,
            onCancel: () => {
              setEmbargoModalOpen(false);
              setPendingEmbargo(null);
            },
            payoutConversion,
            balance: embargoAvailableBalance
          }
        ),
        pendingEmbargo && /* @__PURE__ */ jsxRuntimeExports.jsx(
          EmbargoConfirmModal,
          {
            order: pendingEmbargo,
            balance: embargoAvailableBalance,
            payoutConversion,
            onConfirm: handleEmbargoConfirm,
            onBack: handleEmbargoConfirmBack,
            onAddBalance: handleAddBalance
          }
        )
      ] }),
      referencesModalOpen && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          SimpleServiceOrderModal,
          {
            config: SIMPLE_SERVICES.references,
            currentUserXid,
            onContinue: handleReferencesContinue,
            onCancel: () => {
              setReferencesModalOpen(false);
              setPendingReferences(null);
            },
            payoutConversion,
            balance: referencesAvailableBalance
          }
        ),
        pendingReferences && /* @__PURE__ */ jsxRuntimeExports.jsx(
          SimpleServiceConfirmModal,
          {
            config: SIMPLE_SERVICES.references,
            order: pendingReferences,
            balance: referencesAvailableBalance,
            payoutConversion,
            onConfirm: handleReferencesConfirm,
            onBack: handleReferencesConfirmBack,
            onAddBalance: handleAddBalance
          }
        )
      ] }),
      bountyRevealModalOpen && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          SimpleServiceOrderModal,
          {
            config: SIMPLE_SERVICES["bounty-reveal"],
            currentUserXid,
            onContinue: handleBountyRevealContinue,
            onCancel: () => {
              setBountyRevealModalOpen(false);
              setPendingBountyReveal(null);
            },
            payoutConversion,
            balance: bountyRevealAvailableBalance
          }
        ),
        pendingBountyReveal && /* @__PURE__ */ jsxRuntimeExports.jsx(
          SimpleServiceConfirmModal,
          {
            config: SIMPLE_SERVICES["bounty-reveal"],
            order: pendingBountyReveal,
            balance: bountyRevealAvailableBalance,
            payoutConversion,
            onConfirm: handleBountyRevealConfirm,
            onBack: handleBountyRevealConfirmBack,
            onAddBalance: handleAddBalance
          }
        )
      ] }),
      flightDelayModalOpen && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          FlightDelayOrderModal,
          {
            onContinue: handleFlightDelayContinue,
            onCancel: () => {
              setFlightDelayModalOpen(false);
              setPendingFlightDelay(null);
            },
            payoutConversion,
            balance: flightDelayAvailableBalance
          }
        ),
        pendingFlightDelay && /* @__PURE__ */ jsxRuntimeExports.jsx(
          FlightDelayConfirmModal,
          {
            order: pendingFlightDelay,
            balance: flightDelayAvailableBalance,
            payoutConversion,
            onConfirm: handleFlightDelayConfirm,
            onBack: handleFlightDelayConfirmBack,
            onAddBalance: handleAddBalance
          }
        )
      ] }),
      simpleServiceModalOpen && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          SimpleServiceOrderModal,
          {
            config: SIMPLE_SERVICES[simpleServiceModalOpen],
            currentUserXid,
            onResolveFactionMembers: handleResolveFactionMembers,
            onContinue: handleSimpleServiceContinue,
            onCancel: () => {
              setSimpleServiceModalOpen(null);
              setPendingSimpleService(null);
            },
            payoutConversion,
            balance: simpleServiceAvailableBalance
          }
        ),
        pendingSimpleService && /* @__PURE__ */ jsxRuntimeExports.jsx(
          SimpleServiceConfirmModal,
          {
            config: SIMPLE_SERVICES[pendingSimpleService.kind],
            order: pendingSimpleService,
            balance: simpleServiceAvailableBalance,
            payoutConversion,
            onConfirm: handleSimpleServiceConfirm,
            onBack: handleSimpleServiceConfirmBack,
            onAddBalance: handleAddBalance
          }
        )
      ] }),
      depositModalOpen && /* @__PURE__ */ jsxRuntimeExports.jsx(
        BalanceModal,
        {
          balance,
          payoutConversion,
          onClose: () => setDepositModalOpen(false),
          onWithdraw: handleWithdraw,
          onBeforeWithdraw: requireAuthOrPrompt,
          initialView: balanceModalView,
          firstContractCompleted
        }
      ),
      pendingCancelBuyerOrder && /* @__PURE__ */ jsxRuntimeExports.jsx(
        CancelBuyerOrderModal,
        {
          refundAmount: getBuyerOrderRefund(pendingCancelBuyerOrder),
          onConfirm: handleCancelBuyerOrderConfirm,
          onCancel: handleCancelBuyerOrderDismiss
        }
      ),
      pendingCancelBountyOrder && /* @__PURE__ */ jsxRuntimeExports.jsx(
        CancelBountyOrderModal,
        {
          order: pendingCancelBountyOrder,
          refundAmount: getBountyOrderRefundAmount(pendingCancelBountyOrder),
          payoutConversion,
          onConfirm: handleCancelBountyOrderConfirm,
          onCancel: handleCancelBountyOrderDismiss
        }
      ),
      pendingBountyFulfillmentOrder && !hasActiveFulfillment && /* @__PURE__ */ jsxRuntimeExports.jsx(
        BountyFulfillModal,
        {
          order: pendingBountyFulfillmentOrder,
          onConfirm: handleBountyFulfillConfirm,
          onCancel: handleBountyFulfillCancel
        }
      ),
      pendingRedeemingListing && !hasActiveFulfillment && /* @__PURE__ */ jsxRuntimeExports.jsx(
        RedeemingFulfillModal,
        {
          listing: pendingRedeemingListing,
          onConfirm: handleRedeemingFulfillConfirm,
          onCancel: handleRedeemingFulfillCancel,
          payoutConversion
        }
      ),
      pendingCancelRedeeming && /* @__PURE__ */ jsxRuntimeExports.jsx(
        CancelRedeemingRequestModal,
        {
          refundAmount: getWithdrawTotalDebit(pendingCancelRedeeming.quantity),
          onConfirm: handleCancelRedeemingConfirm,
          onCancel: handleCancelRedeemingDismiss
        }
      ),
      pendingCancelProductivityBoost && /* @__PURE__ */ jsxRuntimeExports.jsx(
        CancelContractConfirmModal,
        {
          description: "This will cancel your productivity boost order and return the escrowed payment.",
          refundAmount: pendingCancelProductivityBoost.escrowedPts,
          onConfirm: handleCancelProductivityBoostConfirm,
          onCancel: handleCancelProductivityBoostDismiss
        }
      ),
      pendingCancelEmbargo && /* @__PURE__ */ jsxRuntimeExports.jsx(
        CancelContractConfirmModal,
        {
          description: "This will cancel your embargo order and return the escrowed payment.",
          refundAmount: pendingCancelEmbargo.escrowedPts,
          onConfirm: handleCancelEmbargoConfirm,
          onCancel: handleCancelEmbargoDismiss
        }
      ),
      pendingCancelReferences && /* @__PURE__ */ jsxRuntimeExports.jsx(
        CancelContractConfirmModal,
        {
          description: "This will cancel your references order and return the escrowed payment.",
          refundAmount: pendingCancelReferences.escrowedPts,
          onConfirm: handleCancelReferencesConfirm,
          onCancel: handleCancelReferencesDismiss
        }
      ),
      pendingCancelBountyReveal && /* @__PURE__ */ jsxRuntimeExports.jsx(
        CancelContractConfirmModal,
        {
          description: "This will cancel your bounty reveal order and return the escrowed payment.",
          refundAmount: pendingCancelBountyReveal.escrowedPts,
          onConfirm: handleCancelBountyRevealConfirm,
          onCancel: handleCancelBountyRevealDismiss
        }
      ),
      archiveModalOpen && /* @__PURE__ */ jsxRuntimeExports.jsx(
        ArchivedReferencesModal,
        {
          references: archivedReferences,
          bountyReveals: archivedBountyReveals,
          onViewReferences: (order) => setViewReferencesReport(order),
          onViewBountyReveal: (order) => setViewBountyRevealReport(order),
          onClose: () => setArchiveModalOpen(false)
        }
      ),
      (viewReferencesReport == null ? void 0 : viewReferencesReport.report) && /* @__PURE__ */ jsxRuntimeExports.jsx(
        ReferencesReportModal,
        {
          targetUserId: viewReferencesReport.targetUserId,
          report: viewReferencesReport.report,
          archived: dismissedReferencesIds.has(viewReferencesReport.id),
          onClose: () => setViewReferencesReport(null),
          onArchive: () => handleArchiveReferences(viewReferencesReport),
          onUnarchive: () => handleUnarchiveReferences(viewReferencesReport)
        }
      ),
      (viewBountyRevealReport == null ? void 0 : viewBountyRevealReport.report) && /* @__PURE__ */ jsxRuntimeExports.jsx(
        BountyRevealReportModal,
        {
          targetUserId: viewBountyRevealReport.targetUserId,
          report: viewBountyRevealReport.report,
          archived: dismissedBountyRevealIds.has(viewBountyRevealReport.id),
          onClose: () => setViewBountyRevealReport(null),
          onArchive: () => handleArchiveBountyReveal(viewBountyRevealReport),
          onUnarchive: () => handleUnarchiveBountyReveal(viewBountyRevealReport)
        }
      ),
      pendingCancelFlightDelay && /* @__PURE__ */ jsxRuntimeExports.jsx(
        CancelContractConfirmModal,
        {
          description: "This will cancel your flight delay order and return the escrowed payment.",
          refundAmount: pendingCancelFlightDelay.escrowedPts,
          onConfirm: handleCancelFlightDelayConfirm,
          onCancel: handleCancelFlightDelayDismiss
        }
      ),
      pendingCancelSimpleService && /* @__PURE__ */ jsxRuntimeExports.jsx(
        CancelContractConfirmModal,
        {
          description: `This will cancel your ${SIMPLE_SERVICES[pendingCancelSimpleService.kind].label.toLowerCase()} order and return the escrowed payment.`,
          refundAmount: pendingCancelSimpleService.escrowedPts,
          onConfirm: handleCancelSimpleServiceConfirm,
          onCancel: handleCancelSimpleServiceDismiss
        }
      ),
      inProgressView && /* @__PURE__ */ jsxRuntimeExports.jsx(
        InProgressContractsModal,
        {
          title: inProgressView.title,
          subtitle: inProgressView.subtitle,
          quantityLabel: inProgressView.quantityLabel,
          parties: inProgressView.parties,
          onClose: () => setInProgressView(null),
          isPaused: (_b = inProgressView.pausableOrder) == null ? void 0 : _b.isPaused,
          onPauseToggle: inProgressView.pausableOrder ? () => handleToggleBuyerOrderPause(
            inProgressView.pausableOrder.id,
            inProgressView.pausableOrder.isPaused
          ) : void 0
        }
      ),
      buyerOrderProgressView && /* @__PURE__ */ jsxRuntimeExports.jsx(
        BuyerOrderProgressModal,
        {
          order: buyerOrderProgressView,
          onClose: () => setBuyerOrderProgressView(null),
          onTogglePause: () => handleToggleBuyerOrderPause(
            buyerOrderProgressView.id,
            buyerOrderProgressView.isPaused
          )
        }
      ),
      referralsModalOpen && session && useBackend && /* @__PURE__ */ jsxRuntimeExports.jsx(
        ReferralsModal,
        {
          summary: referralSummary,
          summaryLoading: referralSummaryLoading,
          referrals: referralList,
          listLoading: referralsListLoading,
          onClose: handleCloseReferrals,
          onApplyReferralCode: handleApplyReferralCode,
          applyError: referralApplyError,
          applying: referralApplying,
          applySuccess: referralApplySuccess
        }
      ),
      apiKeyPromptOpen && /* @__PURE__ */ jsxRuntimeExports.jsx(
        ApiKeySetup,
        {
          onSubmit: handleApiKeyPromptSubmit,
          onClose: () => setApiKeyPromptOpen(false),
          error: auth2.error
        }
      ),
      deleteAccountModalOpen && session && /* @__PURE__ */ jsxRuntimeExports.jsx(
        DeleteAccountModal,
        {
          deleting: deletingAccount,
          error: deleteAccountError,
          onCancel: () => {
            if (!deletingAccount) setDeleteAccountModalOpen(false);
          },
          onConfirm: async () => {
            setDeletingAccount(true);
            setDeleteAccountError(null);
            try {
              await deleteMyAccount(getSupabase(session));
              await auth2.signOut();
              setDeleteAccountModalOpen(false);
              setSettingsOpen(false);
            } catch (err) {
              setDeleteAccountError(
                err instanceof Error ? err.message : "Could not delete account"
              );
            } finally {
              setDeletingAccount(false);
            }
          }
        }
      )
    ] }) }) });
  }
  function injectStyles(shadow, styles2) {
    for (const css of styles2) {
      if (!css.trim()) continue;
      const el = document.createElement("style");
      el.textContent = css;
      shadow.appendChild(el);
    }
  }
  const appStyles = "._root_uz7kd_1 {\n  all: initial;\n  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica,\n    Arial, sans-serif;\n  font-size: 14px;\n  line-height: 1.4;\n  -webkit-font-smoothing: antialiased;\n}\n\n._loading_uz7kd_10 {\n  position: fixed;\n  bottom: 24px;\n  right: 24px;\n  z-index: 2147483645;\n  margin: 0;\n  padding: 10px 14px;\n  border-radius: 6px;\n  background: #1a1a2e;\n  color: #e8e8f0;\n  border: 1px solid #3f43cf;\n  font-size: 13px;\n}\n\n._banner_uz7kd_24 {\n  position: fixed;\n  top: 12px;\n  left: 50%;\n  transform: translateX(-50%);\n  z-index: 2147483651;\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  margin: 0;\n  padding: 8px 14px;\n  border-radius: 6px;\n  background: #3d1f1f;\n  color: #ff8a8a;\n  border: 1px solid #ff6b6b;\n  font-size: 13px;\n  max-width: min(480px, 90vw);\n}\n\n._bannerButton_uz7kd_43 {\n  margin: 0 0 0 10px;\n  padding: 3px 8px;\n  border: 1px solid rgba(255, 138, 138, 0.65);\n  border-radius: 4px;\n  background: rgba(255, 255, 255, 0.08);\n  color: #fff;\n  font: inherit;\n  font-size: 12px;\n  font-weight: 700;\n  cursor: pointer;\n}\n\n._bannerButton_uz7kd_43:hover,\n._bannerButton_uz7kd_43:focus-visible {\n  background: rgba(255, 255, 255, 0.16);\n  outline: none;\n}\n\n._bannerFeature_uz7kd_62 {\n  position: fixed;\n  top: 12px;\n  left: 50%;\n  transform: translateX(-50%);\n  z-index: 2147483651;\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  margin: 0;\n  padding: 8px 14px;\n  border-radius: 6px;\n  background: #1f3d2a;\n  color: #8affa8;\n  border: 1px solid #6bff8a;\n  font-size: 13px;\n  max-width: min(480px, 90vw);\n}\n\n._bannerFeatureButton_uz7kd_81 {\n  margin: 0 0 0 10px;\n  padding: 3px 8px;\n  border: 1px solid rgba(138, 255, 168, 0.65);\n  border-radius: 4px;\n  background: rgba(255, 255, 255, 0.08);\n  color: #fff;\n  font: inherit;\n  font-size: 12px;\n  font-weight: 700;\n  cursor: pointer;\n}\n\n._bannerFeatureButton_uz7kd_81:hover,\n._bannerFeatureButton_uz7kd_81:focus-visible {\n  background: rgba(255, 255, 255, 0.16);\n  outline: none;\n}\n";
  const sidebarStyles = "._backdrop_1yz7u_1 {\n  position: fixed;\n  inset: 0;\n  z-index: 2147483645;\n  margin: 0;\n  padding: 0;\n  border: none;\n  background: rgba(0, 0, 0, 0.45);\n  opacity: 0;\n  pointer-events: none;\n  cursor: pointer;\n  transition: opacity 280ms cubic-bezier(0.4, 0, 0.2, 1);\n}\n\n._backdropVisible_1yz7u_15 {\n  opacity: 1;\n  pointer-events: auto;\n}\n\n._panel_1yz7u_20 {\n  position: fixed;\n  top: 0;\n  right: 0;\n  z-index: 2147483646;\n  display: flex;\n  flex-direction: column;\n  /* Wider than 1/3 viewport when needed so mode-switch labels do not overlap */\n  width: max(33.333vw, 420px);\n  min-width: 420px;\n  max-width: min(480px, calc(100vw - 16px));\n  height: 100vh;\n  background: #1a1d2e;\n  border-left: 1px solid rgba(112, 139, 219, 0.25);\n  box-shadow: -8px 0 32px rgba(0, 0, 0, 0.4);\n  transform: translateX(100%);\n  transition: transform 280ms cubic-bezier(0.4, 0, 0.2, 1);\n  color: #e8eaf0;\n  box-sizing: border-box;\n}\n\n._panelOpen_1yz7u_41 {\n  transform: translateX(0);\n}\n\n._header_1yz7u_45 {\n  flex-shrink: 0;\n  display: flex;\n  flex-direction: column;\n  gap: 16px;\n  padding: 20px 20px 16px;\n  border-bottom: 1px solid rgba(255, 255, 255, 0.08);\n}\n\n._headerRow_1yz7u_54 {\n  display: flex;\n  align-items: flex-start;\n  justify-content: space-between;\n  gap: 12px;\n}\n\n._title_1yz7u_61 {\n  margin: 0;\n  font-size: 18px;\n  font-weight: 700;\n  letter-spacing: -0.02em;\n  color: #fff;\n  /* The brand title must never wrap — the balance text degrades instead. */\n  white-space: nowrap;\n  flex-shrink: 0;\n}\n\n._headerActions_1yz7u_72 {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  /* Allow the actions (balance text) to give way before the title wraps. */\n  min-width: 0;\n}\n\n._settingsButton_1yz7u_80 {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 34px;\n  height: 34px;\n  margin: 0;\n  padding: 0;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  border-radius: 8px;\n  background: rgba(112, 139, 219, 0.1);\n  color: rgba(158, 181, 240, 0.85);\n  cursor: pointer;\n  transition:\n    color 150ms ease,\n    border-color 150ms ease,\n    background 150ms ease;\n}\n\n._settingsButton_1yz7u_80:hover {\n  color: #c8d8ff;\n  border-color: rgba(112, 139, 219, 0.55);\n  background: rgba(112, 139, 219, 0.18);\n}\n\n._settingsButtonActive_1yz7u_105 {\n  color: #fff;\n  border-color: rgba(112, 139, 219, 0.65);\n  background: rgba(63, 67, 207, 0.35);\n  box-shadow: 0 0 0 1px rgba(112, 139, 219, 0.25);\n}\n\n._settingsButton_1yz7u_80:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._balanceButton_1yz7u_117 {\n  flex-shrink: 0;\n  margin: 0;\n  padding: 6px 12px;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  border-radius: 8px;\n  background: rgba(112, 139, 219, 0.1);\n  font-family: inherit;\n  font-size: 14px;\n  font-weight: 700;\n  font-variant-numeric: tabular-nums;\n  color: #9eb5f0;\n  white-space: nowrap;\n  cursor: pointer;\n  transition:\n    background 150ms ease,\n    border-color 150ms ease,\n    color 150ms ease,\n    box-shadow 150ms ease;\n}\n\n._balanceButton_1yz7u_117:hover {\n  background: rgba(112, 139, 219, 0.22);\n  border-color: rgba(112, 139, 219, 0.55);\n  color: #c5d4f7;\n  box-shadow: 0 0 0 1px rgba(112, 139, 219, 0.15);\n}\n\n._balanceButton_1yz7u_117:active {\n  background: rgba(112, 139, 219, 0.28);\n}\n\n._body_1yz7u_149 {\n  flex: 1;\n  min-height: 0;\n  overflow-y: auto;\n  padding: 20px;\n}\n\n._bodyBuying_1yz7u_156,\n._bodyScrollPanel_1yz7u_157 {\n  position: relative;\n  display: flex;\n  flex-direction: column;\n  flex: 1;\n  min-height: 0;\n  overflow: hidden;\n  padding: 16px 20px 20px;\n}\n\n._bodyScrollPanel_1yz7u_157 > *:not(._bodyPanelLockOverlay_1yz7u_167) {\n  flex: 1;\n  min-height: 0;\n  display: flex;\n  flex-direction: column;\n}\n\n._bodyPanelLocked_1yz7u_174 > *:not(._bodyPanelLockOverlay_1yz7u_167) {\n  pointer-events: none;\n  user-select: none;\n  filter: grayscale(0.35);\n  opacity: 0.38;\n}\n\n._bodyPanelLockOverlay_1yz7u_167 {\n  position: absolute;\n  inset: 0;\n  z-index: 10;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  padding: 24px;\n  background: rgba(18, 20, 31, 0.72);\n  text-align: center;\n  pointer-events: auto;\n}\n\n._bodyPanelLockMessage_1yz7u_194 {\n  margin: 0;\n  max-width: 260px;\n  font-size: 14px;\n  font-weight: 600;\n  line-height: 1.5;\n  color: #e8eaf0;\n}\n\n._boardLoading_1yz7u_203 {\n  margin: 24px 16px;\n  font-size: 14px;\n  color: rgba(255, 255, 255, 0.55);\n  text-align: center;\n}\n\n._modeHeading_1yz7u_210 {\n  margin: 0 0 8px;\n  font-size: 15px;\n  font-weight: 600;\n  color: #fff;\n}\n\n._placeholder_1yz7u_217 {\n  margin: 0;\n  font-size: 14px;\n  color: rgba(255, 255, 255, 0.55);\n  line-height: 1.5;\n}\n\n@media (hover: none), (pointer: coarse) {\n  ._panel_1yz7u_20 {\n    inset: 0;\n    width: 100vw;\n    min-width: 0;\n    max-width: 100vw;\n    height: 100dvh;\n    border-left: none;\n    box-shadow: none;\n  }\n\n  ._header_1yz7u_45 {\n    padding-top: max(20px, env(safe-area-inset-top));\n    padding-left: max(20px, env(safe-area-inset-left));\n    padding-right: max(20px, env(safe-area-inset-right));\n  }\n\n  ._body_1yz7u_149,\n  ._bodyBuying_1yz7u_156,\n  ._bodyScrollPanel_1yz7u_157 {\n    padding-bottom: max(20px, env(safe-area-inset-bottom));\n    padding-left: max(20px, env(safe-area-inset-left));\n    padding-right: max(20px, env(safe-area-inset-right));\n  }\n}\n";
  const modeSwitchStyles = "._switch_1kov1_1 {\n  position: relative;\n  display: grid;\n  grid-template-columns: repeat(3, minmax(0, 1fr));\n  gap: 0;\n  width: 100%;\n  min-width: 0;\n  padding: 4px;\n  border-radius: 10px;\n  background: #12141f;\n  border: 1px solid rgba(112, 139, 219, 0.2);\n}\n\n._pillHidden_1kov1_14 {\n  opacity: 0;\n}\n\n._pill_1kov1_14 {\n  position: absolute;\n  top: 4px;\n  left: 4px;\n  width: calc((100% - 8px) / 3);\n  height: calc(100% - 8px);\n  border-radius: 7px;\n  box-shadow: 0 2px 8px rgba(63, 67, 207, 0.35);\n  transition:\n    transform 200ms cubic-bezier(0.4, 0, 0.2, 1),\n    box-shadow 200ms cubic-bezier(0.4, 0, 0.2, 1);\n  pointer-events: none;\n}\n\n._pill_1kov1_14::before,\n._pill_1kov1_14::after {\n  content: '';\n  position: absolute;\n  inset: 0;\n  border-radius: inherit;\n  transition: opacity 200ms cubic-bezier(0.4, 0, 0.2, 1);\n}\n\n._pill_1kov1_14::before {\n  background: linear-gradient(180deg, #708bdb 0%, #3f43cf 100%);\n  opacity: 1;\n}\n\n._pill_1kov1_14::after {\n  background: linear-gradient(#cc7032 0, #b3382c);\n  opacity: 0;\n}\n\n._pillAlert_1kov1_51 {\n  box-shadow: 0 2px 8px rgba(179, 56, 44, 0.35);\n}\n\n._pillAlert_1kov1_51::before {\n  opacity: 0;\n}\n\n._pillAlert_1kov1_51::after {\n  opacity: 1;\n}\n\n._segment_1kov1_63 {\n  position: relative;\n  z-index: 1;\n  padding: 10px 10px;\n  min-width: 0;\n  border: none;\n  border-radius: 7px;\n  background: transparent;\n  color: rgba(255, 255, 255, 0.55);\n  font-family: inherit;\n  font-size: 13px;\n  font-weight: 600;\n  line-height: 1.2;\n  cursor: pointer;\n  transition: color 150ms ease;\n  white-space: nowrap;\n}\n\n._segment_1kov1_63:hover {\n  color: rgba(255, 255, 255, 0.85);\n}\n\n._segment_1kov1_63[aria-selected='true'] {\n  color: #fff;\n}\n\n._segment_1kov1_63:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 1px;\n}\n\n._segmentAlert_1kov1_94:not([aria-selected='true']) {\n  color: #b3382c;\n}\n\n._segmentAlert_1kov1_94:not([aria-selected='true']):hover {\n  color: #cc7032;\n}\n";
  const contractModalStyles = `._overlay_1nw3y_1 {
  position: fixed;
  inset: 0;
  z-index: 2147483648;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: rgba(0, 0, 0, 0.55);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica,
    Arial, sans-serif;
  line-height: 1.4;
  -webkit-font-smoothing: antialiased;
}

._overlayElevated_1nw3y_16 {
  z-index: 2147483649;
}

._overlayElevatedTop_1nw3y_20 {
  z-index: 2147483650;
}

._dialog_1nw3y_24 {
  width: 100%;
  max-width: 380px;
  padding: 22px;
  border-radius: 10px;
  border: 1px solid rgba(112, 139, 219, 0.3);
  background: #1a1d2e;
  color: #e8eaf0;
  box-shadow: 0 16px 48px rgba(0, 0, 0, 0.45);
}

._title_1nw3y_35 {
  margin: 0 0 8px;
  font-size: 17px;
  font-weight: 700;
  color: #fff;
}

/* ── Wallet modal ───────────────────────────────────────────────────── */
._walletHeader_1nw3y_43 {
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;
}

._walletHeader_1nw3y_43 ._title_1nw3y_35 {
  margin: 0;
}

._infoButton_1nw3y_54 {
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  border: 1px solid rgba(112, 139, 219, 0.5);
  background: rgba(112, 139, 219, 0.12);
  color: #9eb5f0;
  font-size: 12px;
  font-weight: 700;
  line-height: 1;
  cursor: pointer;
  transition:
    background 150ms ease,
    color 150ms ease;
}

._infoButton_1nw3y_54:hover,
._infoButton_1nw3y_54[aria-expanded='true'] {
  background: rgba(112, 139, 219, 0.25);
  color: #fff;
}

._infoPopover_1nw3y_80 {
  position: absolute;
  top: calc(100% + 6px);
  left: 0;
  right: 0;
  z-index: 5;
  padding: 12px 14px;
  border-radius: 8px;
  border: 1px solid rgba(112, 139, 219, 0.35);
  background: #12141f;
  box-shadow: 0 10px 28px rgba(0, 0, 0, 0.5);
  font-size: 12.5px;
  line-height: 1.5;
  color: rgba(255, 255, 255, 0.78);
}

._infoPopover_1nw3y_80 strong {
  color: #fff;
  font-weight: 700;
}

._introBanner_1nw3y_101 {
  position: relative;
  display: flex;
  align-items: flex-start;
  gap: 10px;
  margin: 14px 0 0;
  padding: 12px 14px;
  border-radius: 8px;
  background: rgba(108, 173, 43, 0.12);
  border: 1px solid rgba(108, 173, 43, 0.4);
}

._introText_1nw3y_113 {
  margin: 0;
  flex: 1;
  font-size: 12.5px;
  line-height: 1.5;
  color: rgba(255, 255, 255, 0.82);
}

._introText_1nw3y_113 strong {
  color: #c5e89a;
  font-weight: 700;
}

._introDismiss_1nw3y_126 {
  flex-shrink: 0;
  margin: -2px -4px 0 0;
  padding: 2px 6px;
  border: none;
  background: none;
  color: rgba(255, 255, 255, 0.5);
  font-size: 13px;
  line-height: 1;
  cursor: pointer;
}

._introDismiss_1nw3y_126:hover {
  color: #fff;
}

._tabs_1nw3y_142 {
  display: flex;
  gap: 4px;
  margin: 16px 0 16px;
  padding: 4px;
  border-radius: 8px;
  background: #12141f;
  border: 1px solid rgba(112, 139, 219, 0.15);
}

._tab_1nw3y_142 {
  flex: 1;
  padding: 8px 12px;
  border: none;
  border-radius: 6px;
  background: none;
  color: rgba(255, 255, 255, 0.55);
  font-family: inherit;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition:
    background 150ms ease,
    color 150ms ease;
}

._tab_1nw3y_142:hover {
  color: #fff;
}

._tabActive_1nw3y_172 {
  background: linear-gradient(180deg, #708bdb 0%, #3f43cf 100%);
  color: #fff;
}

._tabActive_1nw3y_172:hover {
  color: #fff;
}

._trustNote_1nw3y_181 {
  margin: 10px 0 0;
  font-size: 12px;
  line-height: 1.5;
  color: rgba(255, 255, 255, 0.45);
}

._depositRedirect_1nw3y_188 {
  margin: 12px 0 0;
  padding: 10px 12px;
  border-radius: 6px;
  background: rgba(108, 173, 43, 0.1);
  border: 1px solid rgba(108, 173, 43, 0.3);
  font-size: 12.5px;
  line-height: 1.5;
  color: rgba(255, 255, 255, 0.78);
}

._summarySub_1nw3y_199 {
  display: block;
  margin-top: 2px;
  font-size: 11.5px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.45);
}

._subtitle_1nw3y_207 {
  margin: 0 0 16px;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.55);
  line-height: 1.45;
}

._label_1nw3y_214 {
  display: block;
  margin-bottom: 6px;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  color: rgba(255, 255, 255, 0.5);
}

._input_1nw3y_224 {
  width: 100%;
  box-sizing: border-box;
  padding: 10px 12px;
  border: 1px solid rgba(112, 139, 219, 0.35);
  border-radius: 6px;
  background: #12141f;
  color: #fff;
  font-family: inherit;
  font-size: 15px;
  font-variant-numeric: tabular-nums;
}

._input_1nw3y_224:focus {
  outline: none;
  border-color: #708bdb;
  box-shadow: 0 0 0 2px rgba(112, 139, 219, 0.25);
}

._inputWrap_1nw3y_243 {
  position: relative;
  display: flex;
  align-items: center;
}

._inputWithPostfix_1nw3y_249 {
  padding-right: 108px;
}

._inputPostfix_1nw3y_253 {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  pointer-events: none;
  font-size: 13px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.45);
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
}

._inputError_1nw3y_266 {
  border-color: #e85d6a;
}

._hintBlock_1nw3y_270 {
  margin-top: 6px;
}

._hintBlock_1nw3y_270 ._hint_1nw3y_270 {
  margin: 0 0 8px;
}

._hintBlock_1nw3y_270 ._payout_1nw3y_278 {
  margin: 0;
}

._hintRow_1nw3y_282 {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  gap: 12px;
  margin-top: 6px;
}

._hint_1nw3y_270 {
  margin: 0;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.4);
  flex: 1;
  min-width: 0;
}

._payout_1nw3y_278 {
  margin: 0;
  flex-shrink: 0;
  font-size: 14px;
  font-weight: 700;
  color: #9eb5f0;
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
}

._error_1nw3y_308 {
  margin: 6px 0 0;
  font-size: 12px;
  color: #f0808a;
  line-height: 1.45;
}

._linkButton_1nw3y_315 {
  margin: 0;
  padding: 0;
  border: none;
  background: none;
  font: inherit;
  font-size: inherit;
  color: inherit;
  text-decoration: underline;
  cursor: pointer;
}

._linkButton_1nw3y_315:hover {
  color: #fff;
}

._profileLink_1nw3y_331 {
  color: #9eb5f0;
  font-weight: 600;
  text-decoration: none;
}

._profileLink_1nw3y_331:hover {
  color: #c5d4f7;
  text-decoration: underline;
}

._notice_1nw3y_342 {
  margin: 16px 0 0;
  padding: 12px;
  border-radius: 6px;
  background: rgba(112, 139, 219, 0.1);
  border: 1px solid rgba(112, 139, 219, 0.2);
  font-size: 13px;
  line-height: 1.5;
  color: rgba(255, 255, 255, 0.75);
}

._notice_1nw3y_342 strong {
  color: inherit;
  font-weight: 700;
}

._noticeWarning_1nw3y_358 {
  margin: 10px 0 0;
  padding: 12px;
  border-radius: 6px;
  background: rgba(232, 93, 106, 0.12);
  border: 1px solid rgba(232, 93, 106, 0.35);
  font-size: 13px;
  line-height: 1.5;
  color: #f0808a;
}

._noticeWarningLink_1nw3y_369 {
  color: inherit;
  font-weight: 600;
  text-decoration: underline dotted currentColor;
  text-underline-offset: 3px;
  transition: color 150ms ease;
}

._noticeWarningLink_1nw3y_369:hover {
  color: #fff;
  text-decoration: underline solid #fff;
  text-underline-offset: 3px;
}

._noticeWarningLink_1nw3y_369:focus-visible {
  outline: 2px solid rgba(232, 93, 106, 0.65);
  outline-offset: 2px;
  border-radius: 2px;
}

._targetChecking_1nw3y_389 {
  margin: 10px 0 0;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.45);
}

/* Live target-hittability warning. Glows + pulses so a seller can't miss that
   the person they need to hit is in hospital / travelling. */
._targetAlert_1nw3y_397 {
  margin: 12px 0 0;
  padding: 12px 14px;
  border-radius: 8px;
  background: rgba(232, 60, 70, 0.16);
  border: 1px solid rgba(232, 60, 70, 0.7);
  color: #ffc2c6;
  animation: _targetAlertPulse_1nw3y_1 1.6s ease-in-out infinite;
}

._targetAlertHeading_1nw3y_407 {
  margin: 0;
  font-size: 14px;
  font-weight: 700;
  color: #ff8b92;
  line-height: 1.4;
}

._targetAlertDetail_1nw3y_415 {
  margin: 6px 0 0;
  font-size: 13px;
  line-height: 1.45;
  color: rgba(255, 200, 202, 0.85);
}

@keyframes _targetAlertPulse_1nw3y_1 {
  0%,
  100% {
    box-shadow: 0 0 0 rgba(232, 60, 70, 0);
    border-color: rgba(232, 60, 70, 0.55);
  }
  50% {
    box-shadow: 0 0 16px rgba(232, 60, 70, 0.65);
    border-color: rgba(255, 90, 100, 0.95);
  }
}

@media (prefers-reduced-motion: reduce) {
  ._targetAlert_1nw3y_397 {
    animation: none;
    box-shadow: 0 0 14px rgba(232, 60, 70, 0.5);
  }
}

._summaryList_1nw3y_441 {
  margin: 0;
  padding: 0;
  border: 1px solid rgba(112, 139, 219, 0.15);
  border-radius: 8px;
  overflow: hidden;
  background: #12141f;
}

._summaryRow_1nw3y_450 {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  padding: 12px 14px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}

._summaryRow_1nw3y_450:last-child {
  border-bottom: none;
}

._summaryRow_1nw3y_450 dt {
  margin: 0;
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  color: rgba(255, 255, 255, 0.45);
}

._summaryRow_1nw3y_450 dd {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  color: #fff;
  font-variant-numeric: tabular-nums;
}

._summaryTotal_1nw3y_480 {
  background: rgba(112, 139, 219, 0.08);
}

._summaryTotal_1nw3y_480 dd {
  color: #9eb5f0;
  font-weight: 700;
}

._summaryNegative_1nw3y_489 dd {
  color: #f0808a;
  font-weight: 700;
}

._actions_1nw3y_494 {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

._cancel_1nw3y_500,
._confirm_1nw3y_501 {
  flex: 1;
  padding: 10px 14px;
  border-radius: 6px;
  font-family: inherit;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  border: none;
  transition:
    background 150ms ease,
    color 150ms ease;
}

._cancel_1nw3y_500 {
  background: #252838;
  color: rgba(255, 255, 255, 0.8);
}

._cancel_1nw3y_500:hover {
  background: #2e3348;
  color: #fff;
}

._confirm_1nw3y_501 {
  background: linear-gradient(180deg, #708bdb 0%, #3f43cf 100%);
  color: #fff;
}

._confirm_1nw3y_501:hover {
  filter: brightness(1.08);
}

._confirm_1nw3y_501:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  filter: none;
}

._actionsSplit_1nw3y_540 {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  margin-top: 20px;
}

._actionCompact_1nw3y_548 {
  flex: 0 0 auto;
  padding: 10px 14px;
  border-radius: 6px;
  font-family: inherit;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  border: none;
  transition:
    background 150ms ease,
    filter 150ms ease,
    color 150ms ease;
}

._withdrawButton_1nw3y_563 {
  background: linear-gradient(180deg, #6cad2b 0%, #4d7c1e 100%);
  color: #fff;
}

._withdrawButton_1nw3y_563:hover {
  filter: brightness(1.08);
}

._confirmCompact_1nw3y_572 {
  background: linear-gradient(180deg, #708bdb 0%, #3f43cf 100%);
  color: #fff;
}

._confirmCompact_1nw3y_572:hover {
  filter: brightness(1.08);
}

._confirmCompact_1nw3y_572:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  filter: none;
}

._gotItButton_1nw3y_587 {
  flex: 1;
  min-width: 0;
}

._actionSecondary_1nw3y_592 {
  background: #252838;
  color: rgba(255, 255, 255, 0.8);
}

._actionSecondary_1nw3y_592:hover {
  background: #2e3348;
  color: #fff;
}

/* Compact Pause / Resume button — icon + label, muted amber to read as
   "paused / caution" next to the full-width blue Close button. */
._pauseButton_1nw3y_604 {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  background: #3a2f1c;
  color: #f0c674;
}

._pauseButton_1nw3y_604:hover {
  background: #4a3c24;
  color: #ffd98a;
}

._pauseButton_1nw3y_604:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  filter: none;
}

._checkboxLabel_1nw3y_623 {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  margin-bottom: 16px;
  font-size: 13px;
  line-height: 1.45;
  color: rgba(255, 255, 255, 0.85);
  cursor: pointer;
}

._checkbox_1nw3y_623 {
  flex-shrink: 0;
  width: 16px;
  height: 16px;
  margin-top: 2px;
  accent-color: #708bdb;
  cursor: pointer;
}

._checkbox_1nw3y_623:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

._confirmDanger_1nw3y_648 {
  position: relative;
  overflow: hidden;
  background: rgba(140, 40, 40, 0.35);
  border: 1px solid rgba(180, 60, 60, 0.5);
  color: #ffc8c8;
}

._confirmDanger_1nw3y_648:hover:not(:disabled) {
  filter: brightness(1.08);
  border-color: rgba(220, 80, 80, 0.65);
}

._confirmDangerFill_1nw3y_661 {
  position: absolute;
  inset: 0;
  transform-origin: left center;
  background: rgba(200, 50, 50, 0.75);
  pointer-events: none;
}

._confirmDangerLabel_1nw3y_669 {
  position: relative;
  z-index: 1;
}

._holdHint_1nw3y_674 {
  margin: 10px 0 0;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.4);
  text-align: center;
}
`;
  const apiKeySetupStyles = "._overlay_o0lju_1 {\n  position: fixed;\n  inset: 0;\n  z-index: 2147483650;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  background: rgba(0, 0, 0, 0.55);\n  font-family: Arial, Helvetica, sans-serif;\n}\n\n._overlaySpotlightActive_o0lju_12 {\n  background: transparent;\n}\n\n._card_o0lju_16 {\n  position: relative;\n  width: min(560px, calc(100vw - 32px));\n  padding: 24px;\n  border-radius: 8px;\n  background: #1a1a2e;\n  border: 1px solid #3f43cf;\n  color: #e8e8f0;\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n}\n\n._closeButton_o0lju_29 {\n  position: absolute;\n  top: 12px;\n  right: 12px;\n  z-index: 1;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 28px;\n  height: 28px;\n  padding: 0;\n  border: none;\n  border-radius: 4px;\n  background: transparent;\n  color: #a8adc8;\n  font-size: 22px;\n  line-height: 1;\n  cursor: pointer;\n}\n\n._closeButton_o0lju_29:hover:not(:disabled) {\n  color: #fff;\n  background: rgba(255, 255, 255, 0.08);\n}\n\n._closeButton_o0lju_29:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._closeButton_o0lju_29:disabled {\n  opacity: 0.5;\n  cursor: not-allowed;\n}\n\n._title_o0lju_64 {\n  margin: 0;\n  font-size: 18px;\n  font-weight: 700;\n}\n\n._text_o0lju_70 {\n  margin: 0;\n  font-size: 13px;\n  line-height: 1.45;\n  color: #a8adc8;\n}\n\n._tooltipWrap_o0lju_77 {\n  position: relative;\n  display: inline-flex;\n  align-items: center;\n  margin-left: 4px;\n  vertical-align: middle;\n}\n\n._tooltipTrigger_o0lju_85 {\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  width: 18px;\n  height: 18px;\n  padding: 0;\n  border: 1px solid #5a6088;\n  border-radius: 50%;\n  background: #252840;\n  color: #c8cce0;\n  font-size: 12px;\n  font-weight: 700;\n  line-height: 1;\n  cursor: pointer;\n}\n\n._tooltipTrigger_o0lju_85:hover,\n._tooltipTrigger_o0lju_85:focus-visible {\n  border-color: #708bdb;\n  color: #fff;\n  outline: none;\n}\n\n._tooltip_o0lju_77 {\n  position: absolute;\n  left: 50%;\n  bottom: calc(100% + 8px);\n  transform: translateX(-50%);\n  width: max-content;\n  max-width: 260px;\n  padding: 8px 10px;\n  border-radius: 6px;\n  background: #0f0f1a;\n  border: 1px solid #4a4f7a;\n  color: #e8e8f0;\n  font-size: 12px;\n  line-height: 1.4;\n  text-align: center;\n  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);\n  pointer-events: none;\n  opacity: 0;\n  visibility: hidden;\n  transition: opacity 0.15s ease, visibility 0.15s ease;\n  z-index: 1;\n}\n\n._tooltipWrap_o0lju_77:hover ._tooltip_o0lju_77,\n._tooltipWrap_o0lju_77:focus-within ._tooltip_o0lju_77 {\n  opacity: 1;\n  visibility: visible;\n}\n\n._label_o0lju_138 {\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n  font-size: 13px;\n  font-weight: 600;\n}\n\n._input_o0lju_146 {\n  padding: 10px 12px;\n  border-radius: 4px;\n  border: 1px solid #4a4f7a;\n  background: #0f0f1a;\n  color: #fff;\n  /* >=16px so iOS Safari doesn't auto-zoom on focus. The zoom shifts the\n     visual viewport and throws off the rect-positioned spotlight overlay. */\n  font-size: 16px;\n}\n\n._input_o0lju_146:focus {\n  outline: 2px solid #708bdb;\n  border-color: transparent;\n}\n\n@keyframes _apiKeyInputPulse_o0lju_1 {\n  0%,\n  100% {\n    border-color: #4a4f7a;\n    box-shadow: 0 0 0 0 rgba(112, 139, 219, 0);\n  }\n  50% {\n    border-color: #8aa4ee;\n    box-shadow: 0 0 0 4px rgba(112, 139, 219, 0.45);\n  }\n}\n\n._inputPulse_o0lju_174 {\n  animation: _apiKeyInputPulse_o0lju_1 1.4s ease-in-out infinite;\n}\n\n._inputPulse_o0lju_174:focus {\n  animation: none;\n}\n\n@keyframes _apiKeyButtonPulse_o0lju_1 {\n  0%,\n  100% {\n    box-shadow: 0 0 0 0 rgba(112, 139, 219, 0);\n  }\n  50% {\n    box-shadow: 0 0 0 5px rgba(112, 139, 219, 0.5);\n  }\n}\n\n._buttonPulse_o0lju_192 {\n  animation: _apiKeyButtonPulse_o0lju_1 1.4s ease-in-out infinite;\n}\n\n._actions_o0lju_196 {\n  display: flex;\n  gap: 10px;\n  justify-content: space-between;\n}\n\n._secondaryButton_o0lju_202 {\n  padding: 10px 16px;\n  border: 1px solid #4a4f7a;\n  border-radius: 4px;\n  background: transparent;\n  color: #c8cce0;\n  font-size: 14px;\n  font-weight: 600;\n  cursor: pointer;\n}\n\n._secondaryButton_o0lju_202:disabled {\n  opacity: 0.6;\n  cursor: not-allowed;\n}\n\n._secondaryButton_o0lju_202:hover:not(:disabled) {\n  border-color: #708bdb;\n  color: #fff;\n}\n\n._button_o0lju_192 {\n  padding: 10px 16px;\n  border: none;\n  border-radius: 4px;\n  background: linear-gradient(135deg, #708bdb, #3f43cf);\n  color: #fff;\n  font-size: 14px;\n  font-weight: 700;\n  cursor: pointer;\n}\n\n._button_o0lju_192:disabled {\n  opacity: 0.6;\n  cursor: not-allowed;\n}\n\n._error_o0lju_239 {\n  margin: 0;\n  font-size: 13px;\n  color: #ff6b6b;\n}\n\n._featureError_o0lju_245 {\n  margin: 0;\n  padding: 10px 12px;\n  border-radius: 6px;\n  background: #1f3d2a;\n  color: #8affa8;\n  border: 1px solid #6bff8a;\n  font-size: 13px;\n  line-height: 1.45;\n}\n\n._privacyLink_o0lju_256 {\n  color: #a8b8f0;\n  text-decoration: underline;\n  text-underline-offset: 2px;\n}\n\n._privacyLink_o0lju_256:hover {\n  color: #fff;\n}\n\n._privacyLink_o0lju_256:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n  border-radius: 2px;\n}\n\n._tosSection_o0lju_272 {\n  margin-top: 4px;\n  border-top: 1px solid rgba(74, 79, 122, 0.45);\n  padding-top: 10px;\n}\n\n._tosToggle_o0lju_278 {\n  display: flex;\n  align-items: center;\n  gap: 6px;\n  width: 100%;\n  padding: 0;\n  border: none;\n  background: none;\n  color: #a8adc8;\n  font-size: 12px;\n  font-weight: 600;\n  cursor: pointer;\n  text-align: left;\n}\n\n._tosToggle_o0lju_278:hover {\n  color: #e8e8f0;\n}\n\n._tosChevron_o0lju_297 {\n  display: inline-block;\n  font-size: 11px;\n  transition: transform 0.15s ease;\n}\n\n._tosChevron_o0lju_297[data-open='true'] {\n  transform: rotate(180deg);\n}\n\n._tosTableWrap_o0lju_307 {\n  margin-top: 10px;\n  overflow-x: auto;\n}\n\n._tosTable_o0lju_307 {\n  width: 100%;\n  min-width: 520px;\n  border-collapse: collapse;\n  font-size: 11px;\n  line-height: 1.35;\n}\n\n._tosTable_o0lju_307 th,\n._tosTable_o0lju_307 td {\n  padding: 8px;\n  border: 1px solid #4a4f7a;\n  text-align: left;\n  vertical-align: top;\n}\n\n._tosTable_o0lju_307 th {\n  background: #252840;\n  color: #c8cce0;\n  font-weight: 700;\n}\n\n._tosTable_o0lju_307 td {\n  color: #e8e8f0;\n}\n";
  const buyingPanelStyles = "._panel_15vqv_1 {\n  display: flex;\n  flex-direction: column;\n  flex: 1;\n  min-height: 0;\n}\n\n._typePickerBar_15vqv_8 {\n  flex-shrink: 0;\n  min-height: 44px;\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 10px 12px 12px;\n  border-bottom: 1px solid rgba(112, 139, 219, 0.18);\n  background: #12141f;\n}\n\n._pickerRowMain_15vqv_19 {\n  flex: 1;\n  min-width: 0;\n}\n\n._tableEmpty_15vqv_24 {\n  margin: 0;\n  padding: 0;\n  text-align: center;\n  font-size: 13px;\n  line-height: 1.45;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._tableEmptyState_15vqv_33 {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  gap: 14px;\n  padding: 28px 16px;\n}\n\n._setAlertButton_15vqv_41 {\n  display: inline-flex;\n  align-items: center;\n  gap: 8px;\n  margin: 0;\n  padding: 8px 14px;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  border-radius: 8px;\n  background: rgba(112, 139, 219, 0.1);\n  color: rgba(255, 255, 255, 0.88);\n  font-family: inherit;\n  font-size: 13px;\n  font-weight: 600;\n  line-height: 1;\n  cursor: pointer;\n  appearance: none;\n  -webkit-appearance: none;\n  transition:\n    border-color 150ms ease,\n    background 150ms ease,\n    color 150ms ease;\n}\n\n._setAlertButton_15vqv_41:hover {\n  border-color: rgba(112, 139, 219, 0.55);\n  background: rgba(112, 139, 219, 0.18);\n  color: #fff;\n}\n\n._setAlertButton_15vqv_41:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._tableComingSoon_15vqv_75 {\n  margin: 0;\n  padding: 28px 16px;\n  text-align: center;\n  font-size: 13px;\n  font-weight: 600;\n  line-height: 1.45;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._tableProductivityBoost_15vqv_85 ._tableHeaderRow_15vqv_85,\n._tableProductivityBoost_15vqv_85 ._rowCells_15vqv_86 {\n  grid-template-columns: minmax(0, 1fr) minmax(88px, 1fr);\n}\n\n._tableProductivityBoost_15vqv_85 ._columnHeader_15vqv_90:nth-child(2),\n._tableProductivityBoost_15vqv_85 ._cellPay_15vqv_91 {\n  justify-content: flex-end;\n  text-align: right;\n}\n\n._table_15vqv_24 {\n  display: flex;\n  flex-direction: column;\n  flex: 1;\n  min-height: 0;\n  overflow: hidden;\n  background: #12141f;\n}\n\n._tableHead_15vqv_85 {\n  flex-shrink: 0;\n  border-bottom: 1px solid rgba(112, 139, 219, 0.22);\n  background: #161925;\n}\n\n._tableHeaderRow_15vqv_85 {\n  display: grid;\n  grid-template-columns: minmax(52px, 0.55fr) minmax(64px, 0.65fr) minmax(88px, 1fr);\n  column-gap: 8px;\n}\n\n._columnHeader_15vqv_90 {\n  display: flex;\n  align-items: center;\n  justify-content: flex-start;\n  gap: 6px;\n  margin: 0;\n  padding: 10px 12px;\n  border: none;\n  background: transparent;\n  color: rgba(255, 255, 255, 0.55);\n  font-family: inherit;\n  font-size: 11px;\n  font-weight: 700;\n  text-transform: uppercase;\n  letter-spacing: 0.05em;\n  cursor: pointer;\n  transition:\n    color 150ms ease,\n    background 150ms ease;\n}\n\n._columnHeader_15vqv_90:nth-child(2),\n._columnHeader_15vqv_90:nth-child(3),\n._columnHeaderQuantity_15vqv_140 {\n  justify-content: flex-end;\n  text-align: right;\n}\n\n._columnHeader_15vqv_90:hover {\n  color: #fff;\n  background: rgba(112, 139, 219, 0.08);\n}\n\n._columnHeaderActive_15vqv_150 {\n  color: #9eb5f0;\n  background: rgba(112, 139, 219, 0.1);\n}\n\n._sortIdle_15vqv_155::after {\n  content: '↕';\n  font-size: 10px;\n  opacity: 0.35;\n}\n\n._sortActive_15vqv_161 {\n  font-size: 11px;\n  line-height: 1;\n  color: #708bdb;\n}\n\n._tableBody_15vqv_167 {\n  display: flex;\n  flex-direction: column;\n  flex: 1;\n  min-height: 0;\n}\n\n._list_15vqv_174 {\n  flex: 1;\n  min-height: 0;\n}\n\n/* AnimatedList row chrome → table rows */\n._list_15vqv_174 .scroll-list {\n  padding: 0;\n}\n\n._list_15vqv_174 .item.tlm-table-row-item {\n  padding: 0;\n  margin: 0;\n  background: transparent;\n  border: none;\n  border-radius: 0;\n  border-bottom: 1px solid rgba(255, 255, 255, 0.06);\n  box-shadow: none;\n}\n\n._list_15vqv_174 .item.tlm-table-row-item.selected {\n  background: rgba(112, 139, 219, 0.12);\n  border-bottom-color: rgba(112, 139, 219, 0.2);\n  box-shadow: none;\n}\n\n._list_15vqv_174 .item.tlm-table-row-item:last-child {\n  border-bottom: none;\n}\n\n._tableRow_15vqv_204 {\n  position: relative;\n  padding: 10px 12px;\n  font-variant-numeric: tabular-nums;\n  transition:\n    padding 180ms ease,\n    background 150ms ease;\n}\n\n._rowCells_15vqv_86 {\n  display: grid;\n  grid-template-columns: minmax(52px, 0.55fr) minmax(64px, 0.65fr) minmax(88px, 1fr);\n  column-gap: 8px;\n  align-items: center;\n  transition: opacity 150ms ease;\n}\n\n._tableRowSelectable_15vqv_221:hover,\n._tableRowSelectable_15vqv_221:focus-within {\n  padding-block: 14px;\n}\n\n._cell_15vqv_91 {\n  font-size: 14px;\n  font-weight: 500;\n  color: #e8eaf0;\n  min-width: 0;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n}\n\n._cellQuantity_15vqv_236,\n._cellPay_15vqv_91 {\n  text-align: right;\n  justify-self: end;\n}\n\n._tableBounties_15vqv_242 ._tableHeaderRow_15vqv_85,\n._tableBounties_15vqv_242 ._rowCells_15vqv_86 {\n  grid-template-columns: minmax(64px, 0.65fr) minmax(52px, 0.55fr) minmax(88px, 1fr);\n}\n\n/* Bounties table: quantity column (middle) left-aligned */\n._bountyColumnHeaderQuantity_15vqv_248 {\n  justify-content: flex-start;\n  text-align: left;\n}\n\n._bountyCellQuantity_15vqv_253 {\n  text-align: left;\n  justify-self: start;\n}\n\n._cellSeller_15vqv_258 {\n  color: rgba(255, 255, 255, 0.88);\n}\n\n._sellerLink_15vqv_262 {\n  color: #708bdb;\n  text-decoration: underline;\n  text-underline-offset: 2px;\n  border-radius: 2px;\n  transition:\n    color 150ms ease,\n    background 150ms ease;\n}\n\n._sellerLink_15vqv_262:hover {\n  color: #9eb5f0;\n  background: rgba(112, 139, 219, 0.18);\n}\n\n._sellerLink_15vqv_262:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._cellPay_15vqv_91 {\n  font-weight: 600;\n  color: #9eb5f0;\n}\n\n._takeContractBtn_15vqv_287 {\n  position: absolute;\n  left: 50%;\n  top: 50%;\n  z-index: 2;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  margin: 0;\n  padding: 8px 16px;\n  border: none;\n  border-radius: 6px;\n  background: linear-gradient(180deg, #708bdb 0%, #3f43cf 100%);\n  box-shadow: 0 2px 10px rgba(63, 67, 207, 0.45);\n  color: #fff;\n  font-family: inherit;\n  font-size: 12px;\n  font-weight: 700;\n  line-height: 1.2;\n  letter-spacing: 0.02em;\n  white-space: nowrap;\n  cursor: pointer;\n  opacity: 0;\n  pointer-events: none;\n  transform: translate(-50%, -50%) scale(0.96);\n  transition:\n    opacity 150ms ease,\n    transform 180ms ease,\n    background 150ms ease;\n}\n\n._tableRowSelectable_15vqv_221:hover ._takeContractBtn_15vqv_287,\n._tableRowSelectable_15vqv_221:focus-within ._takeContractBtn_15vqv_287 {\n  opacity: 1;\n  pointer-events: auto;\n  transform: translate(-50%, -50%) scale(1);\n}\n\n/* Force the hover-only button visible while a spotlight tutorial points at it,\n   so the highlighted target is actually shown (not an empty bright gap). */\n._takeContractBtnRevealed_15vqv_327 {\n  opacity: 1;\n  pointer-events: auto;\n  transform: translate(-50%, -50%) scale(1);\n}\n\n._takeContractBtn_15vqv_287:hover {\n  background: linear-gradient(180deg, #9eb5f0 0%, #708bdb 100%);\n}\n\n._takeContractBtn_15vqv_287:focus-visible {\n  opacity: 1;\n  pointer-events: auto;\n  transform: translate(-50%, -50%) scale(1);\n  outline: 2px solid #9eb5f0;\n  outline-offset: 2px;\n}\n\n@media (hover: none), (pointer: coarse) {\n  ._tableRowSelectable_15vqv_221 {\n    padding-block: 14px;\n  }\n\n  ._tableRowSelectable_15vqv_221 ._takeContractBtn_15vqv_287 {\n    opacity: 1;\n    pointer-events: auto;\n    transform: translate(-50%, -50%) scale(1);\n  }\n\n  ._tableRowOwn_15vqv_356 ._cancelRedeem_15vqv_356 {\n    opacity: 1;\n  }\n}\n\n._tableRowHighlighted_15vqv_361 {\n  box-shadow: inset 0 0 0 2px rgba(232, 164, 58, 0.65);\n  background: rgba(232, 164, 58, 0.12);\n}\n\n._tableRowOwn_15vqv_356 {\n  position: relative;\n  box-shadow: inset 0 0 0 1px rgba(112, 139, 219, 0.45);\n  background: rgba(112, 139, 219, 0.1);\n  cursor: default;\n}\n\n._cancelRedeem_15vqv_356 {\n  position: absolute;\n  top: 50%;\n  right: 8px;\n  z-index: 1;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 22px;\n  height: 22px;\n  padding: 0;\n  border: none;\n  border-radius: 4px;\n  background: rgba(0, 0, 0, 0.45);\n  color: #fff;\n  font-size: 16px;\n  line-height: 1;\n  cursor: pointer;\n  transform: translateY(-50%);\n  opacity: 0;\n  transition:\n    opacity 150ms ease,\n    background 150ms ease;\n}\n\n._tableRowOwn_15vqv_356:hover ._cancelRedeem_15vqv_356 {\n  opacity: 1;\n}\n\n._cancelRedeem_15vqv_356:hover {\n  background: rgba(232, 93, 93, 0.85);\n}\n\n._cancelRedeem_15vqv_356:focus-visible {\n  opacity: 1;\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._list_15vqv_174 .item.tlm-table-row-item.selected ._tableRowHighlighted_15vqv_361 {\n  background: rgba(232, 164, 58, 0.18);\n}\n\n._tableRowReserved_15vqv_416 {\n  opacity: 0.6;\n  cursor: default;\n}\n\n._tableRowReserved_15vqv_416:hover {\n  background: transparent;\n}\n\n._cellQuantity_15vqv_236 ._fullyReservedBadge_15vqv_425,\n._bountyCellQuantity_15vqv_253 ._fullyReservedBadge_15vqv_425 {\n  display: inline-flex;\n  align-items: center;\n  justify-content: flex-end;\n  width: 100%;\n  padding: 4px 9px;\n  border: 1px solid rgba(255, 255, 255, 0.15);\n  border-radius: 6px;\n  background: rgba(255, 255, 255, 0.04);\n  color: rgba(255, 255, 255, 0.55);\n  font-size: 10px;\n  font-weight: 700;\n  text-transform: uppercase;\n  letter-spacing: 0.05em;\n  box-sizing: border-box;\n}\n\n/* Notice shown in the References sell table on the website (no scraping). */\n._webSellNotice_15vqv_444 {\n  display: flex;\n  flex-direction: column;\n  gap: 4px;\n  margin: 6px 6px 10px;\n  padding: 10px 12px;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  border-radius: 8px;\n  background: rgba(112, 139, 219, 0.1);\n  font-size: 12px;\n  line-height: 1.45;\n  color: rgba(255, 255, 255, 0.78);\n}\n\n._webSellNoticeTitle_15vqv_458 {\n  font-size: 12.5px;\n  font-weight: 700;\n  color: #fff;\n}\n\n._webSellNotice_15vqv_444 a {\n  color: #9eb5f0;\n  font-weight: 600;\n  text-decoration: underline;\n}\n\n._webSellNotice_15vqv_444 a:hover {\n  color: #c2cdf2;\n}\n";
  const activeContractStyles = "._panel_jmw4q_1 {\n  display: flex;\n  flex-direction: column;\n  flex: 1;\n  min-height: 0;\n  padding: 4px 0;\n  overflow-y: auto;\n  -webkit-overflow-scrolling: touch;\n}\n\n._badge_jmw4q_11 {\n  align-self: flex-start;\n  margin-bottom: 12px;\n  padding: 4px 10px;\n  border-radius: 4px;\n  background: rgba(232, 164, 58, 0.15);\n  border: 1px solid rgba(232, 164, 58, 0.35);\n  font-size: 11px;\n  font-weight: 700;\n  text-transform: uppercase;\n  letter-spacing: 0.05em;\n  color: #e8a43a;\n}\n\n._badgeCompleted_jmw4q_25 {\n  background: rgba(61, 186, 109, 0.15);\n  border-color: rgba(61, 186, 109, 0.35);\n  color: #3dba6d;\n}\n\n._headline_jmw4q_31 {\n  margin: 0 0 24px;\n  font-size: 28px;\n  font-weight: 700;\n  letter-spacing: -0.02em;\n  line-height: 1.15;\n  color: #fff;\n}\n\n._timer_jmw4q_40 {\n  margin: 0;\n  font-size: 42px;\n  font-weight: 700;\n  font-variant-numeric: tabular-nums;\n  color: #fff;\n  letter-spacing: -0.02em;\n  line-height: 1;\n}\n\n._timerHint_jmw4q_50 {\n  margin: 6px 0 24px;\n  font-size: 13px;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._details_jmw4q_56 {\n  display: flex;\n  flex-direction: column;\n  gap: 0;\n  border: 1px solid rgba(112, 139, 219, 0.15);\n  border-radius: 8px;\n  overflow: visible;\n  background: #12141f;\n}\n\n._row_jmw4q_66 {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  gap: 12px;\n  padding: 12px 14px;\n  border-bottom: 1px solid rgba(255, 255, 255, 0.06);\n}\n\n._row_jmw4q_66:last-child {\n  border-bottom: none;\n}\n\n._rowLabel_jmw4q_79 {\n  font-size: 12px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._rowValue_jmw4q_87 {\n  font-size: 15px;\n  font-weight: 600;\n  color: #fff;\n  font-variant-numeric: tabular-nums;\n}\n\n._rowValuePay_jmw4q_94 {\n  font-size: 15px;\n  font-weight: 700;\n  color: #9eb5f0;\n  font-variant-numeric: tabular-nums;\n}\n\n._sellerLink_jmw4q_101 {\n  color: #708bdb;\n  text-decoration: underline;\n  text-underline-offset: 2px;\n  font-size: 15px;\n  font-weight: 600;\n  font-variant-numeric: tabular-nums;\n}\n\n._sellerLink_jmw4q_101:hover {\n  color: #9eb5f0;\n}\n\n._turnInSection_jmw4q_114 {\n  margin-top: auto;\n  padding-top: 20px;\n  display: flex;\n  flex-direction: column;\n  gap: 10px;\n}\n\n._turnInRow_jmw4q_122 {\n  display: flex;\n  align-items: stretch;\n  gap: 10px;\n}\n\n._shortcutButton_jmw4q_128 {\n  flex-shrink: 0;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 72px;\n  min-height: 56px;\n  padding: 8px 6px;\n  border-radius: 10px;\n  border: 1px solid rgba(232, 164, 58, 0.45);\n  background: linear-gradient(180deg, #f0c050 0%, #d8942a 100%);\n  color: #fff;\n  font-size: 13px;\n  font-weight: 800;\n  letter-spacing: 0.02em;\n  text-transform: uppercase;\n  text-decoration: none;\n  cursor: pointer;\n  transition:\n    filter 0.15s ease,\n    transform 0.1s ease;\n}\n\n._shortcutButton_jmw4q_128:hover {\n  filter: brightness(1.08);\n}\n\n._shortcutButton_jmw4q_128:active {\n  transform: scale(0.99);\n}\n\n._partyValue_jmw4q_159 {\n  position: relative;\n  z-index: 2;\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  min-width: 0;\n}\n\n._turnInButton_jmw4q_168 {\n  flex: 1;\n  min-width: 0;\n  padding: 18px 20px;\n  border: none;\n  border-radius: 10px;\n  background: linear-gradient(180deg, #3dba6d 0%, #2a9d5c 100%);\n  color: #fff;\n  font-size: 18px;\n  font-weight: 800;\n  letter-spacing: 0.02em;\n  text-transform: uppercase;\n  cursor: pointer;\n  transition:\n    filter 0.15s ease,\n    transform 0.1s ease;\n}\n\n._turnInButton_jmw4q_168:hover:not(:disabled) {\n  filter: brightness(1.08);\n}\n\n._turnInButton_jmw4q_168:active:not(:disabled) {\n  transform: scale(0.99);\n}\n\n._turnInButton_jmw4q_168:disabled {\n  opacity: 0.65;\n  cursor: wait;\n}\n\n/* First-contract nudge after the shortcut redirect: glow pulse only, no dim. */\n._turnInButtonHighlight_jmw4q_200 {\n  animation: _turnInGlowPulse_jmw4q_1 1.6s ease-in-out infinite;\n}\n\n@keyframes _turnInGlowPulse_jmw4q_1 {\n  0%,\n  100% {\n    box-shadow: 0 0 0 0 rgba(61, 186, 109, 0);\n  }\n  50% {\n    box-shadow:\n      0 0 0 4px rgba(61, 186, 109, 0.45),\n      0 0 18px 6px rgba(61, 186, 109, 0.35);\n  }\n}\n\n._closeButton_jmw4q_216 {\n  width: 100%;\n  padding: 18px 20px;\n  border: none;\n  border-radius: 10px;\n  background: linear-gradient(180deg, #708bdb 0%, #3f43cf 100%);\n  color: #fff;\n  font-size: 18px;\n  font-weight: 800;\n  letter-spacing: 0.02em;\n  text-transform: uppercase;\n  cursor: pointer;\n  transition:\n    filter 0.15s ease,\n    transform 0.1s ease;\n}\n\n._closeButton_jmw4q_216:hover {\n  filter: brightness(1.08);\n}\n\n._closeButton_jmw4q_216:active {\n  transform: scale(0.99);\n}\n\n._turnInError_jmw4q_241 {\n  margin: 0;\n  font-size: 12px;\n  line-height: 1.4;\n  color: #f07178;\n  text-align: center;\n}\n\n@media (hover: none), (pointer: coarse) {\n  ._headline_jmw4q_31 {\n    margin-bottom: 20px;\n    font-size: 24px;\n  }\n\n  ._timer_jmw4q_40 {\n    font-size: 36px;\n  }\n\n  ._timerHint_jmw4q_50 {\n    margin-bottom: 20px;\n  }\n\n  ._turnInButton_jmw4q_168 {\n    padding: 14px 16px;\n    font-size: 16px;\n  }\n}\n";
  const payoutValueStyles = "._button_6731j_1 {\n  display: inline-flex;\n  align-items: center;\n  justify-content: flex-end;\n  min-width: 0;\n  margin: 0;\n  padding: 0;\n  border: 0;\n  border-radius: 2px;\n  background: transparent;\n  color: inherit;\n  font: inherit;\n  font-variant-numeric: inherit;\n  line-height: inherit;\n  cursor: pointer;\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n  text-decoration: underline dotted rgba(158, 181, 240, 0.55);\n  text-underline-offset: 3px;\n  transition: color 150ms ease;\n}\n\n._button_6731j_1:hover,\n._button_6731j_1:focus-visible,\n.tlm-payout-hover-scope:hover ._button_6731j_1,\n.tlm-payout-hover-scope:focus-within ._button_6731j_1 {\n  color: #c5d4f7;\n  text-decoration: underline solid #9eb5f0;\n  text-underline-offset: 3px;\n}\n\n._button_6731j_1:focus-visible {\n  outline: none;\n  box-shadow: 0 0 0 2px rgba(112, 139, 219, 0.6);\n}\n\n._scriptValue_6731j_38,\n._convertedValue_6731j_39 {\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n}\n\n._convertedValue_6731j_39 {\n  display: none;\n}\n\n._button_6731j_1:hover ._scriptValue_6731j_38,\n._button_6731j_1:focus-visible ._scriptValue_6731j_38,\n.tlm-payout-hover-scope:hover ._button_6731j_1 ._scriptValue_6731j_38,\n.tlm-payout-hover-scope:focus-within ._button_6731j_1 ._scriptValue_6731j_38 {\n  display: none;\n}\n\n._button_6731j_1:hover ._convertedValue_6731j_39,\n._button_6731j_1:focus-visible ._convertedValue_6731j_39,\n.tlm-payout-hover-scope:hover ._button_6731j_1 ._convertedValue_6731j_39,\n.tlm-payout-hover-scope:focus-within ._button_6731j_1 ._convertedValue_6731j_39 {\n  display: inline;\n}\n\n._conversion_6731j_63 {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  flex-wrap: wrap;\n  gap: 10px;\n  margin: 4px 0 14px;\n  padding: 18px 16px;\n  border-radius: 10px;\n  background: rgba(112, 139, 219, 0.1);\n  border: 1px solid rgba(112, 139, 219, 0.2);\n}\n\n._fromValue_6731j_76 {\n  font-size: 16px;\n  font-weight: 600;\n  color: rgba(255, 255, 255, 0.7);\n  font-variant-numeric: tabular-nums;\n}\n\n._arrow_6731j_83 {\n  font-size: 16px;\n  color: rgba(255, 255, 255, 0.4);\n}\n\n._toValue_6731j_88 {\n  font-size: 22px;\n  font-weight: 700;\n  color: #9eb5f0;\n  font-variant-numeric: tabular-nums;\n}\n\n._formulaLine_6731j_95 {\n  margin: 0;\n  text-align: center;\n  font-size: 12px;\n  color: rgba(255, 255, 255, 0.4);\n  font-variant-numeric: tabular-nums;\n}\n\n._note_6731j_103 {\n  margin: 14px 0 0;\n  font-size: 12px;\n  line-height: 1.5;\n  color: rgba(255, 255, 255, 0.5);\n  text-align: center;\n}\n";
  const copyIdButtonStyles = "._wrap_1nwp6_1 {\n  position: relative;\n  z-index: 1;\n  display: inline-flex;\n  flex-shrink: 0;\n}\n\n._tooltip_1nwp6_8 {\n  position: absolute;\n  bottom: calc(100% + 8px);\n  left: 50%;\n  transform: translateX(-50%);\n  z-index: 10000;\n  padding: 6px 10px;\n  border-radius: 6px;\n  background: #2a3148;\n  border: 1px solid rgba(112, 139, 219, 0.45);\n  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.35);\n  color: #e8eaf0;\n  font-size: 11px;\n  font-weight: 600;\n  white-space: nowrap;\n  pointer-events: none;\n  animation: _tooltipIn_1nwp6_1 0.15s ease-out;\n}\n\n._tooltip_1nwp6_8::after {\n  content: '';\n  position: absolute;\n  top: 100%;\n  left: 50%;\n  transform: translateX(-50%);\n  border: 5px solid transparent;\n  border-top-color: #2a3148;\n}\n\n@keyframes _tooltipIn_1nwp6_1 {\n  from {\n    opacity: 0;\n    transform: translateX(-50%) translateY(4px);\n  }\n  to {\n    opacity: 1;\n    transform: translateX(-50%) translateY(0);\n  }\n}\n\n._copyButton_1nwp6_48 {\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  width: 32px;\n  height: 32px;\n  padding: 0;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  border-radius: 6px;\n  background: rgba(112, 139, 219, 0.12);\n  color: #9eb5f0;\n  cursor: pointer;\n  transition:\n    background 0.15s ease,\n    color 0.15s ease,\n    border-color 0.15s ease;\n}\n\n._copyButton_1nwp6_48:hover {\n  background: rgba(112, 139, 219, 0.22);\n  color: #fff;\n  border-color: rgba(112, 139, 219, 0.55);\n}\n\n._copyButton_1nwp6_48:active {\n  transform: scale(0.96);\n}\n";
  const buyersPanelStyles = "._panel_1s77q_1 {\n  display: flex;\n  flex-direction: column;\n  flex: 1;\n  min-height: 0;\n  gap: 20px;\n  overflow-y: auto;\n}\n\n._collapsibleSection_1s77q_10 {\n  display: flex;\n  flex-direction: column;\n  gap: 0;\n}\n\n._sectionHeader_1s77q_16 {\n  display: flex;\n  align-items: flex-start;\n  gap: 8px;\n  width: 100%;\n  margin-bottom: 10px;\n}\n\n._sectionHeaderStart_1s77q_24 {\n  display: flex;\n  align-items: center;\n  flex-wrap: wrap;\n  gap: 8px;\n  flex: 1;\n  min-width: 0;\n}\n\n._sectionTitle_1s77q_33 {\n  display: flex;\n  align-items: center;\n  flex-wrap: wrap;\n  gap: 0.35em;\n  margin: 0;\n  font-size: 12px;\n  font-weight: 700;\n  text-transform: uppercase;\n  letter-spacing: 0.05em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._sectionBadges_1s77q_46 {\n  display: inline-flex;\n  align-items: center;\n  flex-wrap: wrap;\n  gap: 6px;\n}\n\n._sectionBadge_1s77q_46 {\n  display: inline-flex;\n  align-items: center;\n  gap: 5px;\n  padding: 3px 8px;\n  border-radius: 6px;\n  font-size: 10px;\n  font-weight: 700;\n  font-variant-numeric: tabular-nums;\n  letter-spacing: 0.03em;\n  line-height: 1.2;\n}\n\n._sectionBadgeBlue_1s77q_66 {\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  background: rgba(112, 139, 219, 0.12);\n  color: #9eb5f0;\n}\n\n._sectionBadgeBlueCancel_1s77q_72:hover,\n._sectionBadgeBlueCancel_1s77q_72:focus-visible {\n  border-color: rgba(232, 93, 93, 0.85);\n  background: rgba(232, 93, 93, 0.2);\n  color: #f0808a;\n}\n\n._sectionBadgeYellow_1s77q_79 {\n  border: 1px solid rgba(232, 164, 58, 0.55);\n  background: rgba(232, 164, 58, 0.16);\n  color: #e8a43a;\n}\n\n._sectionBadgeYellow_1s77q_79:hover,\n._sectionBadgeYellow_1s77q_79:focus-visible {\n  background: rgba(232, 164, 58, 0.26);\n  border-color: rgba(232, 164, 58, 0.85);\n  color: #f0b14a;\n}\n\n/* Paused buyer order — muted slate, distinct from open (blue) / in-progress\n   (amber) / completed (amber). */\n._sectionBadgePaused_1s77q_94 {\n  border: 1px solid rgba(148, 163, 184, 0.45);\n  background: rgba(148, 163, 184, 0.14);\n  color: #c2ccda;\n}\n\n._sectionBadgePaused_1s77q_94:hover,\n._sectionBadgePaused_1s77q_94:focus-visible {\n  background: rgba(148, 163, 184, 0.24);\n  border-color: rgba(148, 163, 184, 0.75);\n  color: #d8e0ea;\n}\n\n._sectionBadgeGreen_1s77q_107 {\n  border: 1px solid rgba(74, 222, 128, 0.35);\n  background: rgba(74, 222, 128, 0.1);\n  color: #86efac;\n}\n\n._sectionBadgeGreenCancel_1s77q_113:hover,\n._sectionBadgeGreenCancel_1s77q_113:focus-visible {\n  border-color: rgba(232, 93, 93, 0.85);\n  background: rgba(232, 93, 93, 0.2);\n  color: #f0808a;\n}\n\n._sectionBadgeNeutral_1s77q_120 {\n  border: 1px solid rgba(255, 255, 255, 0.2);\n  background: rgba(255, 255, 255, 0.06);\n  color: rgba(255, 255, 255, 0.85);\n}\n\n._sectionBadgeNeutralCancel_1s77q_126:hover,\n._sectionBadgeNeutralCancel_1s77q_126:focus-visible {\n  border-color: rgba(232, 93, 93, 0.85);\n  background: rgba(232, 93, 93, 0.2);\n  color: #f0808a;\n}\n\n._sectionBadgeRed_1s77q_133 {\n  border: 1px solid rgba(248, 113, 113, 0.35);\n  background: rgba(248, 113, 113, 0.1);\n  color: #fca5a5;\n}\n\n._sectionBadgeRedCancel_1s77q_139:hover,\n._sectionBadgeRedCancel_1s77q_139:focus-visible {\n  border-color: rgba(232, 93, 93, 0.85);\n  background: rgba(232, 93, 93, 0.2);\n  color: #f0808a;\n}\n\n._sectionBadgeButton_1s77q_146 {\n  margin: 0;\n  font-family: inherit;\n  cursor: pointer;\n  transition:\n    background 150ms ease,\n    border-color 150ms ease,\n    filter 150ms ease;\n}\n\n._sectionBadgeButton_1s77q_146:hover {\n  filter: brightness(1.08);\n}\n\n._sectionBadgeButton_1s77q_146:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._sectionBadgeIcon_1s77q_165 {\n  flex-shrink: 0;\n  opacity: 0.9;\n}\n\n._sectionBadgeCount_1s77q_170 {\n  font-variant-numeric: tabular-nums;\n}\n\n._sectionBadgeLabel_1s77q_174 {\n  flex-shrink: 0;\n}\n\n._sectionBadgeCountdown_1s77q_178 {\n  color: rgba(255, 255, 255, 0.75);\n  font-weight: 600;\n  font-variant-numeric: tabular-nums;\n}\n\n._sectionChevronButton_1s77q_184 {\n  flex-shrink: 0;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 28px;\n  height: 28px;\n  margin: 0 0 0 auto;\n  padding: 0;\n  border: 1px solid rgba(112, 139, 219, 0.2);\n  border-radius: 6px;\n  background: rgba(112, 139, 219, 0.08);\n  color: rgba(255, 255, 255, 0.45);\n  cursor: pointer;\n  transition:\n    background 150ms ease,\n    border-color 150ms ease,\n    color 150ms ease;\n}\n\n._sectionChevronButton_1s77q_184:hover {\n  background: rgba(112, 139, 219, 0.16);\n  border-color: rgba(112, 139, 219, 0.35);\n  color: rgba(255, 255, 255, 0.72);\n}\n\n._sectionChevronButton_1s77q_184:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._sectionChevron_1s77q_184 {\n  flex-shrink: 0;\n  transition: transform 150ms ease;\n}\n\n._sectionChevronExpanded_1s77q_220 {\n  transform: rotate(180deg);\n  color: rgba(255, 255, 255, 0.72);\n}\n\n._sectionBody_1s77q_225 {\n  display: flex;\n  flex-direction: column;\n  gap: 0;\n}\n\n._openList_1s77q_231 {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n}\n\n._openCard_1s77q_237 {\n  position: relative;\n  padding: 12px 14px;\n  border-radius: 8px;\n  border: 1px solid rgba(112, 139, 219, 0.2);\n  background: #12141f;\n}\n\n._cancelOrder_1s77q_245 {\n  position: absolute;\n  top: 8px;\n  right: 8px;\n  z-index: 1;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 22px;\n  height: 22px;\n  padding: 0;\n  border: none;\n  border-radius: 4px;\n  background: rgba(0, 0, 0, 0.45);\n  color: #fff;\n  font-size: 16px;\n  line-height: 1;\n  cursor: pointer;\n  opacity: 0;\n  transition:\n    opacity 150ms ease,\n    background 150ms ease;\n}\n\n._openCardOwn_1s77q_269:hover ._cancelOrder_1s77q_245,\n._openCardWithdraw_1s77q_270:hover ._cancelOrder_1s77q_245,\n._openCardEmbargo_1s77q_271:hover ._cancelOrder_1s77q_245,\n._openCardSimpleService_1s77q_272:hover ._cancelOrder_1s77q_245,\n._openCardOwn_1s77q_269:focus-within ._cancelOrder_1s77q_245,\n._openCardWithdraw_1s77q_270:focus-within ._cancelOrder_1s77q_245,\n._openCardEmbargo_1s77q_271:focus-within ._cancelOrder_1s77q_245,\n._openCardSimpleService_1s77q_272:focus-within ._cancelOrder_1s77q_245 {\n  opacity: 1;\n}\n\n._cancelOrder_1s77q_245:hover {\n  background: rgba(232, 93, 93, 0.85);\n}\n\n._cancelOrder_1s77q_245:focus-visible {\n  opacity: 1;\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n@media (hover: none), (pointer: coarse) {\n  ._openCardOwn_1s77q_269 ._cancelOrder_1s77q_245,\n  ._openCardWithdraw_1s77q_270 ._cancelOrder_1s77q_245,\n  ._openCardEmbargo_1s77q_271 ._cancelOrder_1s77q_245,\n  ._openCardSimpleService_1s77q_272 ._cancelOrder_1s77q_245,\n  ._openCardClosed_1s77q_295 ._cancelOrder_1s77q_245 {\n    opacity: 1;\n  }\n}\n\n._openCardActive_1s77q_300 {\n  border-color: rgba(232, 164, 58, 0.45);\n  background: rgba(232, 164, 58, 0.08);\n}\n\n._openCardOwn_1s77q_269 {\n  border-color: rgba(112, 139, 219, 0.35);\n  background: rgba(112, 139, 219, 0.08);\n  transition:\n    border-color 150ms ease,\n    background 150ms ease;\n}\n\n._openCardOwn_1s77q_269:hover,\n._openCardOwn_1s77q_269:focus-visible {\n  border-color: rgba(112, 139, 219, 0.5);\n  background: rgba(112, 139, 219, 0.12);\n}\n\n._openCardClickable_1s77q_319 {\n  cursor: pointer;\n}\n\n._openCardClickable_1s77q_319:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._openCardClosed_1s77q_295 {\n  border-color: rgba(232, 164, 58, 0.55);\n  background: rgba(232, 164, 58, 0.08);\n  transition:\n    border-color 150ms ease,\n    background 150ms ease;\n}\n\n._openCardClosed_1s77q_295:hover,\n._openCardClosed_1s77q_295:focus-visible {\n  border-color: rgba(232, 164, 58, 0.75);\n  background: rgba(232, 164, 58, 0.14);\n}\n\n._openCardClosed_1s77q_295:hover ._cancelOrder_1s77q_245,\n._openCardClosed_1s77q_295:focus-within ._cancelOrder_1s77q_245 {\n  opacity: 1;\n}\n\n._openCardWithdraw_1s77q_270 {\n  border-color: rgba(74, 222, 128, 0.35);\n  background: rgba(74, 222, 128, 0.08);\n}\n\n._openCardEmbargo_1s77q_271 {\n  border-color: rgba(248, 113, 113, 0.35);\n  background: rgba(248, 113, 113, 0.08);\n}\n\n._openCardSimpleService_1s77q_272 {\n  border-color: rgba(228, 228, 231, 0.3);\n  background: rgba(228, 228, 231, 0.07);\n}\n\n._openCardBadge_1s77q_362 {\n  display: inline-block;\n  margin-bottom: 8px;\n  font-size: 10px;\n  font-weight: 700;\n  text-transform: uppercase;\n  letter-spacing: 0.05em;\n  color: #9eb5f0;\n}\n\n._openCardBadgeGreen_1s77q_372 {\n  color: #6ee7a0;\n}\n\n._openCardBadgeClosed_1s77q_376 {\n  color: #e8a43a;\n}\n\n._openCardBadgePaused_1s77q_380 {\n  color: #c2ccda;\n}\n\n._sectionBadgeCompound_1s77q_384 {\n  gap: 0;\n  padding: 0;\n  overflow: hidden;\n}\n\n._sectionBadgeCompoundMain_1s77q_390 {\n  padding: 3px 6px 3px 8px;\n  border: none;\n  background: transparent;\n  color: inherit;\n}\n\n._sectionBadgeCompoundDismiss_1s77q_397 {\n  padding: 3px 7px 3px 4px;\n  border: none;\n  border-left: 1px solid rgba(232, 164, 58, 0.35);\n  background: transparent;\n  color: inherit;\n  font-size: 12px;\n  line-height: 1;\n}\n\n._sectionBadgeCompoundDismiss_1s77q_397:hover,\n._sectionBadgeCompoundDismiss_1s77q_397:focus-visible {\n  background: rgba(232, 93, 93, 0.2);\n  color: #f0808a;\n}\n\n._servicesButtons_1s77q_413 {\n  display: grid;\n  grid-template-columns: repeat(3, minmax(0, 1fr));\n  gap: 8px;\n}\n\n@media (max-width: 360px) {\n  ._servicesButtons_1s77q_413 {\n    grid-template-columns: 1fr;\n  }\n}\n\n._openCardBadgeRed_1s77q_425 {\n  color: #fca5a5;\n}\n\n._openCardBadgeGray_1s77q_429 {\n  color: #e4e4e7;\n}\n\n._openCardActive_1s77q_300 ._openCardBadge_1s77q_362 {\n  color: #e8a43a;\n}\n\n._inProgressBadge_1s77q_437 {\n  position: absolute;\n  top: 8px;\n  right: 8px;\n  z-index: 1;\n  display: inline-flex;\n  align-items: center;\n  gap: 6px;\n  margin: 0;\n  padding: 4px 9px;\n  border: 1px solid rgba(232, 164, 58, 0.55);\n  border-radius: 6px;\n  background: rgba(232, 164, 58, 0.16);\n  color: #e8a43a;\n  font-family: inherit;\n  font-size: 10px;\n  font-weight: 700;\n  text-transform: uppercase;\n  letter-spacing: 0.05em;\n  cursor: pointer;\n  transition:\n    background 150ms ease,\n    border-color 150ms ease,\n    color 150ms ease,\n    transform 150ms ease;\n}\n\n._inProgressBadge_1s77q_437:hover {\n  background: rgba(232, 164, 58, 0.26);\n  border-color: rgba(232, 164, 58, 0.85);\n  color: #f0b14a;\n}\n\n._inProgressBadge_1s77q_437:active {\n  transform: translateY(1px);\n}\n\n._inProgressBadge_1s77q_437:focus-visible {\n  outline: 2px solid #e8a43a;\n  outline-offset: 2px;\n}\n\n._inProgressDot_1s77q_479 {\n  width: 6px;\n  height: 6px;\n  border-radius: 50%;\n  background: #e8a43a;\n  box-shadow: 0 0 6px rgba(232, 164, 58, 0.6);\n}\n\n._openCardRows_1s77q_487 {\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n}\n\n._openCardRow_1s77q_487 {\n  display: flex;\n  justify-content: space-between;\n  gap: 12px;\n  font-size: 13px;\n}\n\n._openCardLabel_1s77q_500 {\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._openCardValue_1s77q_504 {\n  font-weight: 600;\n  color: #fff;\n  font-variant-numeric: tabular-nums;\n}\n\n._form_1s77q_510 {\n  display: flex;\n  flex-direction: column;\n  gap: 14px;\n  padding: 16px;\n  border-radius: 8px;\n  border: 1px solid rgba(112, 139, 219, 0.18);\n  background: #12141f;\n}\n\n._field_1s77q_520 {\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n}\n\n._label_1s77q_526 {\n  display: flex;\n  align-items: baseline;\n  flex-wrap: wrap;\n  gap: 6px;\n  font-size: 12px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.5);\n}\n\n._labelText_1s77q_538 {\n  flex-shrink: 0;\n}\n\n._labelPostfix_1s77q_542 {\n  font-size: 12px;\n  font-weight: 600;\n  text-transform: none;\n  letter-spacing: normal;\n  color: rgba(255, 255, 255, 0.45);\n  font-variant-numeric: tabular-nums;\n}\n\n._labelPostfixWarning_1s77q_551 {\n  color: #f87171;\n}\n\n._timelyLossHint_1s77q_555 {\n  margin-left: auto;\n  font-size: 12px;\n  font-weight: 600;\n  text-transform: lowercase;\n  letter-spacing: normal;\n  color: #f87171;\n  white-space: nowrap;\n}\n\n._input_1s77q_565 {\n  box-sizing: border-box;\n  width: 100%;\n  padding: 10px 12px;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  border-radius: 6px;\n  background: #1a1d2e;\n  color: #fff;\n  font-family: inherit;\n  font-size: 15px;\n  font-variant-numeric: tabular-nums;\n}\n\n._inputWrap_1s77q_578 {\n  position: relative;\n  display: flex;\n  align-items: center;\n}\n\n._inputWithSuffix_1s77q_584 {\n  padding-right: 48px;\n}\n\n._inputSuffix_1s77q_588 {\n  position: absolute;\n  right: 12px;\n  top: 50%;\n  transform: translateY(-50%);\n  pointer-events: none;\n  font-size: 12px;\n  font-weight: 700;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._input_1s77q_565:focus {\n  outline: none;\n  border-color: #708bdb;\n  box-shadow: 0 0 0 2px rgba(112, 139, 219, 0.25);\n}\n\n._inputError_1s77q_606 {\n  border-color: #e85d6a;\n}\n\n._totalRow_1s77q_610 {\n  display: flex;\n  align-items: baseline;\n  justify-content: space-between;\n  gap: 12px;\n  padding-top: 4px;\n}\n\n._totalLabel_1s77q_618 {\n  font-size: 13px;\n  font-weight: 600;\n  color: rgba(255, 255, 255, 0.55);\n}\n\n._totalValue_1s77q_624 {\n  font-size: 18px;\n  font-weight: 700;\n  color: #9eb5f0;\n  font-variant-numeric: tabular-nums;\n}\n\n._error_1s77q_631 {\n  margin: 0;\n  font-size: 12px;\n  color: #f0808a;\n}\n\n._submit_1s77q_637 {\n  margin-top: 4px;\n  padding: 11px 14px;\n  border: none;\n  border-radius: 6px;\n  background: linear-gradient(180deg, #708bdb 0%, #3f43cf 100%);\n  color: #fff;\n  font-family: inherit;\n  font-size: 14px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: filter 150ms ease;\n}\n\n._submit_1s77q_637:hover {\n  filter: brightness(1.08);\n}\n\n._submit_1s77q_637:disabled {\n  opacity: 0.5;\n  cursor: not-allowed;\n  filter: none;\n}\n\n._formDisabled_1s77q_661 {\n  margin: 0;\n  padding: 14px;\n  border-radius: 8px;\n  border: 1px solid rgba(112, 139, 219, 0.15);\n  background: #12141f;\n  font-size: 13px;\n  line-height: 1.45;\n  color: rgba(255, 255, 255, 0.5);\n}\n";
  const insurancePolicyModalStyles = "._dialog_199qm_1 {\n  width: 100%;\n  max-width: 420px;\n  height: 520px;\n  max-height: min(90vh, 520px);\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n}\n\n._modalMain_199qm_11 {\n  flex: 1;\n  min-height: 0;\n  display: flex;\n  flex-direction: column;\n}\n\n._selectionSlot_199qm_18 {\n  flex-shrink: 0;\n  margin: 0 0 12px;\n}\n\n._selectionSummary_199qm_23 {\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n  margin: 0;\n  padding: 10px 12px;\n  border-radius: 8px;\n  border: 1px solid rgba(112, 139, 219, 0.2);\n  background: rgba(112, 139, 219, 0.06);\n  list-style: none;\n}\n\n._selectionItem_199qm_35 {\n  display: flex;\n  align-items: baseline;\n  justify-content: space-between;\n  gap: 10px;\n  font-size: 12px;\n}\n\n._selectionLabel_199qm_43 {\n  flex-shrink: 0;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.4);\n}\n\n._selectionValue_199qm_51 {\n  text-align: right;\n  font-weight: 600;\n  color: #9eb5f0;\n  line-height: 1.35;\n}\n\n._selectionValueWithLink_199qm_58 {\n  color: #9eb5f0;\n}\n\n._selectionValuePlaceholder_199qm_62 {\n  color: rgba(255, 255, 255, 0.22);\n  font-weight: 600;\n}\n\n._stepViewport_199qm_67 {\n  flex: 1;\n  min-height: 0;\n  overflow: hidden;\n  position: relative;\n}\n\n._stepPanel_199qm_74 {\n  height: 100%;\n  overflow-y: auto;\n  padding-right: 2px;\n  backface-visibility: hidden;\n}\n\n._stepPanelForward_199qm_81 {\n  animation: _stepSlideForward_199qm_1 380ms cubic-bezier(0.22, 1, 0.36, 1) both;\n  will-change: transform, opacity;\n}\n\n._stepPanelBack_199qm_86 {\n  animation: _stepSlideBack_199qm_1 380ms cubic-bezier(0.22, 1, 0.36, 1) both;\n  will-change: transform, opacity;\n}\n\n@keyframes _stepSlideForward_199qm_1 {\n  from {\n    opacity: 0;\n    transform: translateX(32px);\n  }\n  to {\n    opacity: 1;\n    transform: translateX(0);\n  }\n}\n\n@keyframes _stepSlideBack_199qm_1 {\n  from {\n    opacity: 0;\n    transform: translateX(-32px);\n  }\n  to {\n    opacity: 1;\n    transform: translateX(0);\n  }\n}\n\n._footer_199qm_113 {\n  flex-shrink: 0;\n  margin-top: 12px;\n}\n\n._stepper_199qm_118 {\n  display: flex;\n  align-items: center;\n  margin: 0 0 16px;\n  padding: 0;\n  list-style: none;\n}\n\n._stepperSegment_199qm_126 {\n  display: contents;\n}\n\n._step_199qm_67 {\n  flex: 0 0 auto;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  gap: 4px;\n  min-width: 48px;\n}\n\n._stepConnector_199qm_139 {\n  flex: 1;\n  position: relative;\n  height: 2px;\n  margin: 0 4px;\n  margin-bottom: 14px;\n  padding: 0;\n  list-style: none;\n}\n\n._stepConnectorTrack_199qm_149 {\n  position: absolute;\n  inset: 0;\n  border-radius: 1px;\n  background: rgba(112, 139, 219, 0.22);\n}\n\n._stepConnectorFill_199qm_156 {\n  position: absolute;\n  inset: 0;\n  border-radius: 1px;\n  background: linear-gradient(90deg, #4ade80 0%, #6ee7a0 100%);\n  transform: scaleX(0);\n  transform-origin: left center;\n  box-shadow: 0 0 8px rgba(74, 222, 128, 0.45);\n}\n\n._stepConnectorFillComplete_199qm_166 {\n  transform: scaleX(1);\n  transition: none;\n}\n\n._stepConnectorFillShoot_199qm_171 {\n  animation: _connectorShoot_199qm_1 520ms cubic-bezier(0.22, 1, 0.36, 1) forwards;\n}\n\n@keyframes _connectorShoot_199qm_1 {\n  0% {\n    transform: scaleX(0);\n    box-shadow: 0 0 0 rgba(74, 222, 128, 0);\n  }\n  70% {\n    box-shadow: 0 0 12px rgba(74, 222, 128, 0.65);\n  }\n  100% {\n    transform: scaleX(1);\n    box-shadow: 0 0 6px rgba(74, 222, 128, 0.35);\n  }\n}\n\n._stepDot_199qm_189 {\n  width: 8px;\n  height: 8px;\n  border-radius: 50%;\n  background: rgba(112, 139, 219, 0.25);\n  transition:\n    background 220ms ease,\n    box-shadow 220ms ease,\n    transform 220ms ease;\n}\n\n._stepActive_199qm_200 ._stepDot_199qm_189 {\n  background: #708bdb;\n  box-shadow: 0 0 8px rgba(112, 139, 219, 0.5);\n  transform: scale(1.15);\n}\n\n._stepComplete_199qm_206 ._stepDot_199qm_189 {\n  background: #6ee7a0;\n  box-shadow: 0 0 8px rgba(110, 231, 160, 0.45);\n}\n\n._stepLabel_199qm_211 {\n  font-size: 9px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.32);\n  text-align: center;\n}\n\n._stepActive_199qm_200 ._stepLabel_199qm_211,\n._stepComplete_199qm_206 ._stepLabel_199qm_211 {\n  color: rgba(255, 255, 255, 0.55);\n}\n\n/* Red variant — applied via `stepperRed` modifier on the .stepper element. */\n._stepperRed_199qm_226 ._stepConnectorFill_199qm_156 {\n  background: linear-gradient(90deg, #ef4444 0%, #f87171 100%);\n  box-shadow: 0 0 8px rgba(248, 113, 113, 0.45);\n}\n\n._stepperRed_199qm_226 ._stepComplete_199qm_206 ._stepDot_199qm_189 {\n  background: #f87171;\n  box-shadow: 0 0 8px rgba(248, 113, 113, 0.45);\n}\n\n/* Gray variant — applied via `stepperGray` modifier on the .stepper element. */\n._stepperGray_199qm_237 ._stepConnectorFill_199qm_156 {\n  background: linear-gradient(90deg, #a1a1aa 0%, #e4e4e7 100%);\n  box-shadow: 0 0 8px rgba(228, 228, 231, 0.4);\n}\n\n._stepperGray_199qm_237 ._stepComplete_199qm_206 ._stepDot_199qm_189 {\n  background: #e4e4e7;\n  box-shadow: 0 0 8px rgba(228, 228, 231, 0.4);\n}\n\n\n._block_199qm_248 {\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n  padding: 0;\n  border: none;\n  margin: 0;\n  height: 100%;\n}\n\n._blockTitle_199qm_258 {\n  margin: 0;\n  font-size: 11px;\n  font-weight: 700;\n  text-transform: uppercase;\n  letter-spacing: 0.06em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._planList_199qm_267 {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n  margin: 0;\n  padding: 0;\n  list-style: none;\n}\n\n._planCard_199qm_276 {\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n  width: 100%;\n  margin: 0;\n  padding: 12px 14px;\n  border: 1px solid rgba(112, 139, 219, 0.22);\n  border-radius: 8px;\n  background: #12141f;\n  color: inherit;\n  font-family: inherit;\n  text-align: left;\n  cursor: pointer;\n  transition:\n    border-color 150ms ease,\n    background 150ms ease,\n    transform 150ms ease;\n}\n\n._planCard_199qm_276:hover:not(:disabled) {\n  border-color: rgba(112, 139, 219, 0.4);\n  background: #161925;\n}\n\n._planCardSelected_199qm_301 {\n  border-color: rgba(112, 139, 219, 0.55);\n  background: rgba(112, 139, 219, 0.1);\n  box-shadow: 0 0 0 1px rgba(112, 139, 219, 0.2);\n}\n\n._planCardBlocked_199qm_307 {\n  opacity: 0.55;\n  cursor: not-allowed;\n}\n\n._planCardHeader_199qm_312 {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  gap: 10px;\n}\n\n._planCardTitle_199qm_319 {\n  font-size: 14px;\n  font-weight: 700;\n  color: #fff;\n}\n\n._planCardBadges_199qm_325 {\n  display: flex;\n  flex-wrap: wrap;\n  gap: 6px;\n  justify-content: flex-end;\n}\n\n._planBadge_199qm_332 {\n  padding: 3px 8px;\n  border-radius: 4px;\n  background: rgba(112, 139, 219, 0.18);\n  font-size: 10px;\n  font-weight: 700;\n  letter-spacing: 0.04em;\n  text-transform: uppercase;\n  color: #9eb5f0;\n}\n\n._planBadgeMultiplier_199qm_343 {\n  background: rgba(74, 222, 128, 0.14);\n  color: #6ee7a0;\n}\n\n._planCardSubtitle_199qm_348 {\n  margin: 0;\n  font-size: 12px;\n  line-height: 1.4;\n  color: rgba(255, 255, 255, 0.5);\n}\n\n._field_199qm_355 {\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n}\n\n._fieldLabel_199qm_361 {\n  font-size: 12px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.5);\n}\n\n._coverageSegments_199qm_369 {\n  position: relative;\n  display: grid;\n  grid-template-columns: repeat(4, minmax(0, 1fr));\n  gap: 0;\n  width: 100%;\n  min-width: 0;\n  padding: 4px;\n  border-radius: 10px;\n  border: 1px solid rgba(112, 139, 219, 0.2);\n  background: #12141f;\n}\n\n._coverageSegmentPill_199qm_382 {\n  position: absolute;\n  top: 4px;\n  left: 4px;\n  width: calc((100% - 8px) / 4);\n  height: calc(100% - 8px);\n  border-radius: 7px;\n  background: rgba(74, 222, 128, 0.22);\n  box-shadow:\n    0 1px 3px rgba(0, 0, 0, 0.22),\n    inset 0 1px 0 rgba(255, 255, 255, 0.06);\n  transition: transform 200ms cubic-bezier(0.4, 0, 0.2, 1);\n  pointer-events: none;\n}\n\n._coverageSegment_199qm_369 {\n  position: relative;\n  z-index: 1;\n  min-width: 0;\n  margin: 0;\n  padding: 10px 6px;\n  border: none;\n  border-radius: 7px;\n  background: transparent;\n  color: rgba(255, 255, 255, 0.55);\n  font-family: inherit;\n  font-size: 12px;\n  font-weight: 600;\n  line-height: 1.2;\n  letter-spacing: 0.02em;\n  cursor: pointer;\n  transition: color 150ms ease;\n}\n\n._coverageSegment_199qm_369:hover {\n  color: rgba(255, 255, 255, 0.85);\n}\n\n._coverageSegment_199qm_369[aria-checked='true'] {\n  color: #6ee7a0;\n}\n\n._coverageSegment_199qm_369:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 1px;\n}\n\n._coveragePayoutBar_199qm_429 {\n  flex-shrink: 0;\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  gap: 12px;\n  margin-top: 12px;\n  padding: 14px 16px;\n  border-radius: 8px;\n  border: 1px solid rgba(74, 222, 128, 0.28);\n  background: rgba(74, 222, 128, 0.08);\n}\n\n._coveragePayoutBarLabel_199qm_442 {\n  font-size: 14px;\n  font-weight: 600;\n  line-height: 1.3;\n  color: rgba(255, 255, 255, 0.88);\n}\n\n._coveragePayoutBarValue_199qm_449 {\n  font-size: 18px;\n  font-weight: 700;\n  line-height: 1.2;\n  color: #6ee7a0;\n  font-variant-numeric: tabular-nums;\n  text-align: right;\n}\n\n._coveragePayoutBarValuePlaceholder_199qm_458 {\n  color: rgba(255, 255, 255, 0.28);\n  font-size: 16px;\n}\n\n._input_199qm_463 {\n  box-sizing: border-box;\n  width: 100%;\n  padding: 10px 12px;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  border-radius: 6px;\n  background: #12141f;\n  color: #fff;\n  font-family: inherit;\n  font-size: 15px;\n  font-variant-numeric: tabular-nums;\n}\n\n._inputWrap_199qm_476 {\n  position: relative;\n  display: flex;\n  align-items: center;\n}\n\n._inputWithSuffix_199qm_482 {\n  padding-right: 48px;\n}\n\n._inputSuffix_199qm_486 {\n  position: absolute;\n  right: 12px;\n  top: 50%;\n  transform: translateY(-50%);\n  pointer-events: none;\n  font-size: 12px;\n  font-weight: 700;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._input_199qm_463:focus {\n  outline: none;\n  border-color: #708bdb;\n  box-shadow: 0 0 0 2px rgba(112, 139, 219, 0.25);\n}\n\n._inputError_199qm_504 {\n  border-color: #e85d6a;\n}\n\n._payoutPreview_199qm_508 {\n  display: flex;\n  align-items: baseline;\n  justify-content: space-between;\n  gap: 12px;\n  margin-top: 8px;\n  font-size: 13px;\n}\n\n._payoutPreviewLabel_199qm_517 {\n  color: rgba(255, 255, 255, 0.5);\n}\n\n._payoutPreviewValue_199qm_521 {\n  font-weight: 700;\n  color: #6ee7a0;\n  font-variant-numeric: tabular-nums;\n}\n\n._payoutBonusNote_199qm_527 {\n  margin: 4px 0 0;\n  font-size: 11px;\n  line-height: 1.4;\n  color: rgba(110, 231, 160, 0.75);\n}\n\n._reviewHint_199qm_534 {\n  margin: 0;\n  padding: 8px 0;\n  font-size: 14px;\n  line-height: 1.5;\n  color: rgba(255, 255, 255, 0.6);\n}\n\n._autoRenewLabel_199qm_542 {\n  display: flex;\n  align-items: flex-start;\n  gap: 10px;\n  margin: 0;\n  font-size: 13px;\n  line-height: 1.45;\n  color: rgba(255, 255, 255, 0.75);\n  cursor: pointer;\n}\n\n._autoRenewCheckbox_199qm_553 {\n  flex-shrink: 0;\n  width: 16px;\n  height: 16px;\n  margin-top: 2px;\n  accent-color: #708bdb;\n}\n\n._summaryPanel_199qm_561 {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n  padding: 14px;\n  border-radius: 8px;\n  border: 1px solid rgba(74, 222, 128, 0.2);\n  background: rgba(74, 222, 128, 0.06);\n}\n\n._summaryRow_199qm_571 {\n  display: flex;\n  align-items: baseline;\n  justify-content: space-between;\n  gap: 12px;\n  font-size: 13px;\n}\n\n._summaryLabel_199qm_579 {\n  color: rgba(255, 255, 255, 0.5);\n}\n\n._summaryValue_199qm_583 {\n  font-weight: 700;\n  color: #9eb5f0;\n  font-variant-numeric: tabular-nums;\n}\n\n._summaryValueHighlight_199qm_589 {\n  color: #6ee7a0;\n}\n\n._discountRow_199qm_593 {\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n}\n\n._discountChip_199qm_599 {\n  display: inline-flex;\n  align-items: center;\n  padding: 6px 10px;\n  border-radius: 6px;\n  border: 1px solid rgba(74, 222, 128, 0.35);\n  background: rgba(74, 222, 128, 0.1);\n  font-size: 11px;\n  font-weight: 600;\n  color: #86efac;\n  line-height: 1.35;\n}\n\n._discountChipFaction_199qm_612 {\n  border-color: rgba(112, 139, 219, 0.35);\n  background: rgba(112, 139, 219, 0.12);\n  color: #9eb5f0;\n}\n\n._discountChipSkeleton_199qm_618 {\n  min-height: 32px;\n  border-color: rgba(112, 139, 219, 0.15);\n  background: rgba(112, 139, 219, 0.08);\n  animation: _insurancePulse_199qm_1 1.2s ease-in-out infinite;\n}\n\n._discountMuted_199qm_625 {\n  margin: 0;\n  font-size: 12px;\n  color: rgba(255, 255, 255, 0.4);\n}\n\n._bonusSection_199qm_631 {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n}\n\n._coveragePayoutPanel_199qm_637 {\n  margin-top: auto;\n  display: flex;\n  flex-direction: column;\n  gap: 14px;\n}\n\n._sectionHeaderRow_199qm_644 {\n  display: flex;\n  align-items: baseline;\n  justify-content: space-between;\n  gap: 10px;\n}\n\n._sectionTitle_199qm_651 {\n  margin: 0;\n  font-size: 11px;\n  font-weight: 700;\n  text-transform: uppercase;\n  letter-spacing: 0.06em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._bonusTitle_199qm_660 {\n  margin: 0;\n  font-size: 11px;\n  font-weight: 700;\n  text-transform: uppercase;\n  letter-spacing: 0.06em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._payoutBreakdownSection_199qm_669 {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n}\n\n._payoutBreakdownTotal_199qm_675 {\n  font-size: 12px;\n  font-weight: 700;\n  color: #6ee7a0;\n  font-variant-numeric: tabular-nums;\n}\n\n._payoutBreakdownTotalValue_199qm_682 {\n  color: inherit;\n}\n\n._payoutEquation_199qm_686 {\n  display: flex;\n  flex-direction: column;\n  gap: 4px;\n  padding: 10px 12px;\n  border-radius: 8px;\n  border: 1px solid rgba(112, 139, 219, 0.2);\n  background: rgba(112, 139, 219, 0.06);\n}\n\n._payoutEquationStep_199qm_696 {\n  display: grid;\n  grid-template-columns: 42px minmax(0, 1fr) auto minmax(72px, auto);\n  align-items: baseline;\n  gap: 6px;\n  font-size: 11px;\n  line-height: 1.35;\n}\n\n._payoutEquationStepTotal_199qm_705 {\n  margin-top: 2px;\n  padding-top: 6px;\n  border-top: 1px solid rgba(112, 139, 219, 0.14);\n}\n\n._payoutEquationTag_199qm_711 {\n  font-size: 9px;\n  font-weight: 700;\n  text-transform: uppercase;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.32);\n}\n\n._payoutEquationExpr_199qm_719 {\n  display: flex;\n  flex-wrap: wrap;\n  align-items: baseline;\n  gap: 4px;\n  min-width: 0;\n  color: rgba(255, 255, 255, 0.72);\n  font-variant-numeric: tabular-nums;\n}\n\n._payoutEquationOperand_199qm_729 {\n  font-weight: 600;\n}\n\n._payoutEquationOp_199qm_729 {\n  color: rgba(255, 255, 255, 0.35);\n  font-weight: 600;\n}\n\n._payoutEquationFactor_199qm_738 {\n  font-weight: 700;\n  color: #9eb5f0;\n}\n\n._payoutEquationEquals_199qm_743 {\n  color: rgba(255, 255, 255, 0.28);\n  font-weight: 600;\n}\n\n._payoutEquationResult_199qm_748 {\n  text-align: right;\n  font-weight: 700;\n  color: rgba(255, 255, 255, 0.55);\n  font-variant-numeric: tabular-nums;\n}\n\n._payoutEquationResultTotal_199qm_755 {\n  color: #6ee7a0;\n}\n\n._bonusList_199qm_759 {\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n}\n\n._bonusRow_199qm_765 {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  gap: 10px;\n  padding: 8px 10px;\n  border-radius: 6px;\n  border: 1px solid rgba(112, 139, 219, 0.18);\n  background: rgba(112, 139, 219, 0.05);\n}\n\n._bonusRowInactive_199qm_776 {\n  opacity: 0.55;\n}\n\n._bonusRowSkeleton_199qm_780 {\n  min-height: 36px;\n  animation: _insurancePulse_199qm_1 1.2s ease-in-out infinite;\n}\n\n._bonusBadge_199qm_785 {\n  flex-shrink: 0;\n  padding: 4px 8px;\n  border-radius: 4px;\n  border: 1px solid rgba(74, 222, 128, 0.35);\n  background: rgba(74, 222, 128, 0.1);\n  font-size: 10px;\n  font-weight: 700;\n  letter-spacing: 0.03em;\n  color: #86efac;\n}\n\n._bonusBadgeFaction_199qm_797 {\n  border-color: rgba(112, 139, 219, 0.35);\n  background: rgba(112, 139, 219, 0.12);\n  color: #9eb5f0;\n}\n\n._bonusMeta_199qm_803 {\n  display: flex;\n  align-items: baseline;\n  justify-content: flex-end;\n  flex-wrap: wrap;\n  gap: 8px;\n  min-width: 0;\n}\n\n._bonusMultiplier_199qm_812 {\n  font-size: 12px;\n  font-weight: 700;\n  color: rgba(255, 255, 255, 0.55);\n  font-variant-numeric: tabular-nums;\n}\n\n._bonusExtra_199qm_819 {\n  font-size: 12px;\n  font-weight: 700;\n  color: #6ee7a0;\n  font-variant-numeric: tabular-nums;\n}\n\n._bonusExtraZero_199qm_826 {\n  color: rgba(255, 255, 255, 0.35);\n}\n\n._bonusExtraValue_199qm_830 {\n  color: inherit;\n}\n\n._confirmCostGroup_199qm_834 {\n  margin: 12px 0 0;\n  border-radius: 8px;\n  border: 1px solid rgba(112, 139, 219, 0.2);\n  background: rgba(112, 139, 219, 0.06);\n  overflow: hidden;\n}\n\n._confirmCostRow_199qm_842 {\n  display: flex;\n  align-items: baseline;\n  justify-content: space-between;\n  gap: 10px;\n  padding: 10px 12px;\n  font-size: 12px;\n}\n\n._confirmCostRow_199qm_842 + ._confirmCostRow_199qm_842 {\n  border-top: 1px solid rgba(112, 139, 219, 0.14);\n}\n\n._confirmBalanceRow_199qm_855 {\n  display: flex;\n  align-items: baseline;\n  justify-content: space-between;\n  gap: 10px;\n  margin: 12px 0 0;\n  padding: 10px 12px;\n  border-radius: 8px;\n  border: 1px solid rgba(112, 139, 219, 0.2);\n  background: rgba(112, 139, 219, 0.06);\n  font-size: 12px;\n}\n\n._confirmBalanceLabel_199qm_868 {\n  flex-shrink: 0;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.4);\n}\n\n._confirmBalanceValue_199qm_876 {\n  text-align: right;\n  font-weight: 700;\n  color: #9eb5f0;\n  font-variant-numeric: tabular-nums;\n}\n\n@keyframes _insurancePulse_199qm_1 {\n  0%,\n  100% {\n    opacity: 0.5;\n  }\n  50% {\n    opacity: 1;\n  }\n}\n\n._error_199qm_893 {\n  margin: 0;\n  font-size: 12px;\n  color: #f0808a;\n}\n\n._hint_199qm_899 {\n  margin: 0;\n  font-size: 12px;\n  color: rgba(255, 255, 255, 0.4);\n  line-height: 1.4;\n}\n\n._errorSlot_199qm_906 {\n  flex-shrink: 0;\n  min-height: 0;\n  margin-top: 8px;\n}\n";
  const serviceBentoCardStyles = "._card_4yqq6_1 {\n  position: relative;\n  display: flex;\n  flex-direction: column;\n  justify-content: space-between;\n  box-sizing: border-box;\n  width: 100%;\n  min-width: 0;\n  margin: 0;\n  overflow: hidden;\n  border: 1px solid var(--bento-border);\n  border-radius: 12px;\n  background: var(--bento-bg);\n  color: var(--bento-fg);\n  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);\n  font-family: inherit;\n  font-size: inherit;\n  text-align: left;\n  appearance: none;\n  -webkit-appearance: none;\n  transition:\n    box-shadow 150ms ease,\n    background 150ms ease,\n    border-color 150ms ease,\n    filter 150ms ease;\n}\n\n._cardInteractive_4yqq6_28 {\n  cursor: pointer;\n}\n\n._card_4yqq6_1:hover {\n  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);\n}\n\n._cardDisabled_4yqq6_36 {\n  opacity: 0.42;\n  cursor: default;\n  filter: grayscale(0.85);\n  pointer-events: none;\n}\n\n._cardDisabled_4yqq6_36:hover {\n  box-shadow: none;\n}\n\n._sizeGrid_4yqq6_47 {\n  aspect-ratio: 1;\n  padding: 10px;\n}\n\n._sizeModalTile_4yqq6_52 {\n  flex: 1;\n  min-height: 132px;\n  padding: 12px;\n}\n\n._topBlock_4yqq6_58 {\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n  min-width: 0;\n  transition: transform 300ms ease;\n}\n\n._sizeGrid_4yqq6_47 ._icon_4yqq6_66 {\n  width: 34px;\n  height: 34px;\n}\n\n._sizeGrid_4yqq6_47 ._title_4yqq6_71 {\n  font-size: 12px;\n  font-weight: 600;\n  line-height: 1.2;\n}\n\n._sizeGrid_4yqq6_47 ._description_4yqq6_77 {\n  font-size: 9px;\n  line-height: 1.3;\n}\n\n._sizeGrid_4yqq6_47 ._bookCta_4yqq6_82 {\n  padding: 14px 10px 10px;\n}\n\n._sizeGrid_4yqq6_47 ._bookCtaLabel_4yqq6_86 {\n  font-size: 9px;\n}\n\n._sizeModalTile_4yqq6_52 ._icon_4yqq6_66 {\n  width: 36px;\n  height: 36px;\n}\n\n._sizeModalTile_4yqq6_52 ._title_4yqq6_71 {\n  font-size: 13px;\n  font-weight: 600;\n  line-height: 1.2;\n}\n\n._sizeModalTile_4yqq6_52 ._description_4yqq6_77 {\n  font-size: 10px;\n  line-height: 1.35;\n}\n\n._sizeModalTile_4yqq6_52 ._bookCta_4yqq6_82 {\n  padding: 16px 12px 12px;\n}\n\n._sizeModalTile_4yqq6_52 ._bookCtaLabel_4yqq6_86 {\n  font-size: 10px;\n}\n\n._icon_4yqq6_66 {\n  flex-shrink: 0;\n  color: var(--bento-icon);\n  transition: transform 300ms ease;\n}\n\n._title_4yqq6_71 {\n  margin: 0;\n  font-weight: 600;\n  line-height: 1.2;\n  color: var(--bento-fg);\n}\n\n._description_4yqq6_77 {\n  margin: 0;\n  color: var(--bento-items);\n  transition: transform 300ms ease;\n  overflow-wrap: anywhere;\n}\n\n._bookCta_4yqq6_82 {\n  pointer-events: none;\n  position: absolute;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  opacity: 0;\n  transform: translateY(100%);\n  transition:\n    transform 300ms ease,\n    opacity 300ms ease;\n}\n\n._bookCtaLabel_4yqq6_86 {\n  font-size: 0.875rem;\n  font-weight: 500;\n  color: var(--bento-fg);\n}\n\n/* Reveal animation — shared by panel grid cards and interactive modal tiles */\n._cardInteractive_4yqq6_28:hover ._topBlock_4yqq6_58 {\n  transform: translateY(-4px);\n}\n\n._cardInteractive_4yqq6_28:hover ._icon_4yqq6_66 {\n  transform: scale(0.9);\n}\n\n._cardInteractive_4yqq6_28:hover ._description_4yqq6_77 {\n  transform: translateY(-20px);\n}\n\n._cardInteractive_4yqq6_28:hover ._bookCta_4yqq6_82 {\n  opacity: 1;\n  transform: translateY(0);\n}\n";
  const serviceBentoThemeStyles = "/* Neutral — WIP */\n._variantNeutral_1iai8_2 {\n  --bento-border: rgba(255, 255, 255, 0.12);\n  --bento-bg: rgba(255, 255, 255, 0.04);\n  --bento-fg: rgba(255, 255, 255, 0.85);\n  --bento-icon: rgba(255, 255, 255, 0.7);\n  --bento-items: rgba(255, 255, 255, 0.45);\n  --bento-hover-bg: rgba(255, 255, 255, 0.06);\n  --bento-hover-border: rgba(255, 255, 255, 0.18);\n  --bento-focus: rgba(255, 255, 255, 0.5);\n}\n\n/* Disrupt — from BountiesButton */\n._variantDisrupt_1iai8_14 {\n  --bento-border: rgba(248, 113, 113, 0.35);\n  --bento-bg: rgba(248, 113, 113, 0.08);\n  --bento-fg: #fca5a5;\n  --bento-icon: #fca5a5;\n  --bento-items: rgba(252, 165, 165, 0.65);\n  --bento-hover-bg: rgba(248, 113, 113, 0.14);\n  --bento-hover-border: rgba(248, 113, 113, 0.55);\n  --bento-focus: #f87171;\n}\n\n/* Other — from OdInsuranceButton */\n._variantOther_1iai8_26 {\n  --bento-border: rgba(74, 222, 128, 0.35);\n  --bento-bg: rgba(74, 222, 128, 0.08);\n  --bento-fg: #86efac;\n  --bento-icon: #86efac;\n  --bento-items: rgba(134, 239, 172, 0.65);\n  --bento-hover-bg: rgba(74, 222, 128, 0.14);\n  --bento-hover-border: rgba(74, 222, 128, 0.55);\n  --bento-focus: #6ee7a0;\n}\n\n._variantNeutralInteractive_1iai8_37:hover {\n  background: var(--bento-hover-bg);\n  border-color: var(--bento-hover-border);\n  filter: brightness(1.05);\n}\n\n._variantNeutralInteractive_1iai8_37:focus-visible {\n  outline: 2px solid var(--bento-focus);\n  outline-offset: 2px;\n}\n\n._variantDisruptInteractive_1iai8_48:hover {\n  background: var(--bento-hover-bg);\n  border-color: var(--bento-hover-border);\n  filter: brightness(1.05);\n}\n\n._variantDisruptInteractive_1iai8_48:focus-visible {\n  outline: 2px solid var(--bento-focus);\n  outline-offset: 2px;\n}\n\n._variantOtherInteractive_1iai8_59:hover {\n  background: var(--bento-hover-bg);\n  border-color: var(--bento-hover-border);\n  filter: brightness(1.05);\n}\n\n._variantOtherInteractive_1iai8_59:focus-visible {\n  outline: 2px solid var(--bento-focus);\n  outline-offset: 2px;\n}\n";
  const serviceCategoryModalStyles = '._dialogWide_8c2s7_1 {\n  max-width: 480px;\n}\n\n._header_8c2s7_5 {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  margin-bottom: 8px;\n}\n\n._headerTitle_8c2s7_12 {\n  margin: 0;\n  line-height: 1.2;\n}\n\n._headerIcon_8c2s7_17 {\n  flex-shrink: 0;\n  width: 24px;\n  height: 24px;\n  color: var(--bento-icon);\n}\n\n/* Matches BuyersPanel.servicesButtons */\n._serviceTileGrid_8c2s7_25 {\n  display: grid;\n  grid-template-columns: repeat(3, minmax(0, 1fr));\n  gap: 8px;\n  margin: 16px 0 0;\n  padding: 0;\n  list-style: none;\n}\n\n._serviceTileItem_8c2s7_34 {\n  display: flex;\n  flex-direction: column;\n  min-width: 0;\n}\n\n/* Coming soon layout: a 3x2 grid of square tiles. "Spies" pins to the\n   top-left and "Friend or Foe" pins to the spot directly below it. */\n._wipTileGrid_8c2s7_42 {\n  display: grid;\n  grid-template-columns: repeat(3, minmax(0, 1fr));\n  grid-auto-rows: minmax(132px, auto);\n  gap: 8px;\n  margin: 16px 0 0;\n  padding: 0;\n  list-style: none;\n}\n\n._wipFeaturedItem_8c2s7_52 {\n  grid-column: 1;\n  grid-row: 2;\n}\n';
  const bountyOrderModalStyles = "._dialog_9mjj2_1 {\n  width: 100%;\n  max-width: 420px;\n  height: 520px;\n  max-height: min(90vh, 520px);\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n}\n\n._block_9mjj2_11 {\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n  margin: 0;\n  padding: 0;\n  border: none;\n  height: 100%;\n}\n\n._fieldHint_9mjj2_21 {\n  margin: 6px 0 0;\n  font-size: 12px;\n  color: rgba(255, 255, 255, 0.4);\n  line-height: 1.45;\n}\n\n._bountyStepDotActive_9mjj2_28 {\n  background: #f87171 !important;\n  box-shadow: 0 0 8px rgba(248, 113, 113, 0.5) !important;\n  transform: scale(1.15);\n}\n\n._bountyStepDotComplete_9mjj2_34 {\n  background: #fca5a5 !important;\n  box-shadow: 0 0 8px rgba(252, 165, 165, 0.45) !important;\n}\n\n._bountyStepLabelActive_9mjj2_39,\n._bountyStepLabelComplete_9mjj2_40 {\n  color: #fca5a5 !important;\n}\n\n._bountyStepConnectorFill_9mjj2_44 {\n  background: linear-gradient(90deg, #f87171 0%, #fca5a5 100%) !important;\n  box-shadow: 0 0 8px rgba(248, 113, 113, 0.45) !important;\n}\n\n._bountyStepConnectorFillShoot_9mjj2_49 {\n  animation: _bountyConnectorShoot_9mjj2_1 520ms cubic-bezier(0.22, 1, 0.36, 1) forwards;\n}\n\n@keyframes _bountyConnectorShoot_9mjj2_1 {\n  0% {\n    transform: scaleX(0);\n    box-shadow: 0 0 0 rgba(248, 113, 113, 0);\n  }\n  70% {\n    box-shadow: 0 0 12px rgba(248, 113, 113, 0.65);\n  }\n  100% {\n    transform: scaleX(1);\n    box-shadow: 0 0 6px rgba(248, 113, 113, 0.35);\n  }\n}\n\n._totalCostBlock_9mjj2_67 {\n  margin-top: 16px;\n  padding-top: 16px;\n  border-top: 1px solid rgba(112, 139, 219, 0.2);\n  display: flex;\n  flex-direction: column;\n  gap: 10px;\n}\n\n._costRow_9mjj2_76 {\n  display: flex;\n  align-items: baseline;\n  justify-content: space-between;\n  gap: 12px;\n  font-size: 13px;\n  color: #9eb5f0;\n}\n\n._costRowLabel_9mjj2_85 {\n  color: rgba(255, 255, 255, 0.55);\n  font-weight: 600;\n}\n\n._costRowTotal_9mjj2_90 {\n  margin-top: 4px;\n  padding-top: 10px;\n  border-top: 1px solid rgba(112, 139, 219, 0.15);\n  font-size: 14px;\n  font-weight: 700;\n}\n\n._costRowTotal_9mjj2_90 ._costRowLabel_9mjj2_85 {\n  color: #9eb5f0;\n}\n\n._costRowValue_9mjj2_102 {\n  font-weight: 600;\n  color: #9eb5f0;\n  font-variant-numeric: tabular-nums;\n}\n\n._costRowTotal_9mjj2_90 ._costRowValue_9mjj2_102 {\n  font-weight: 700;\n}\n\n._slotFeeValue_9mjj2_112 {\n  color: #9eb5f0;\n  font-weight: 600;\n  font-variant-numeric: tabular-nums;\n}\n";
  const tornPrimaryValueStyles = "._primaryDisplay_17aop_1,\n._altDisplay_17aop_2 {\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n}\n\n._primaryDisplay_17aop_1 {\n  display: inline;\n}\n\n._altDisplay_17aop_2 {\n  display: none;\n}\n\n._button_17aop_16:hover ._primaryDisplay_17aop_1,\n._button_17aop_16:focus-visible ._primaryDisplay_17aop_1,\n.tlm-payout-hover-scope:hover ._button_17aop_16 ._primaryDisplay_17aop_1,\n.tlm-payout-hover-scope:focus-within ._button_17aop_16 ._primaryDisplay_17aop_1 {\n  display: none;\n}\n\n._button_17aop_16:hover ._altDisplay_17aop_2,\n._button_17aop_16:focus-visible ._altDisplay_17aop_2,\n.tlm-payout-hover-scope:hover ._button_17aop_16 ._altDisplay_17aop_2,\n.tlm-payout-hover-scope:focus-within ._button_17aop_16 ._altDisplay_17aop_2 {\n  display: inline;\n}\n";
  const activeBountyOrderCardStyles = "._card_1wr24_1 {\n  border-color: rgba(248, 113, 113, 0.35);\n  background: rgba(248, 113, 113, 0.08);\n}\n\n._card_1wr24_1:hover {\n  border-color: rgba(248, 113, 113, 0.5);\n  background: rgba(248, 113, 113, 0.12);\n}\n\n._badge_1wr24_11 {\n  color: #fca5a5;\n  margin-bottom: 0;\n}\n\n._targetLink_1wr24_16 {\n  color: #fca5a5;\n  font-weight: 600;\n  text-decoration: none;\n}\n\n._targetLink_1wr24_16:hover {\n  color: #fecaca;\n  text-decoration: underline;\n}\n\n._targetSep_1wr24_27 {\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._payoutValue_1wr24_31 {\n  color: #fca5a5;\n}\n";
  const activeInsuranceCardStyles = "._card_19t6u_1 {\n  padding-top: 14px;\n  border-color: rgba(74, 222, 128, 0.35);\n  background: rgba(74, 222, 128, 0.08);\n  cursor: pointer;\n  transition:\n    border-color 150ms ease,\n    background 150ms ease;\n}\n\n._card_19t6u_1:hover,\n._card_19t6u_1:focus-visible {\n  border-color: rgba(74, 222, 128, 0.5);\n  background: rgba(74, 222, 128, 0.12);\n}\n\n._card_19t6u_1:focus-visible {\n  outline: 2px solid #4ade80;\n  outline-offset: 2px;\n}\n\n._badge_19t6u_22 {\n  color: #6ee7a0;\n  margin-bottom: 0;\n}\n\n._badgeRow_19t6u_27 {\n  display: flex;\n  align-items: center;\n  flex-wrap: wrap;\n  gap: 6px;\n  margin-bottom: 8px;\n}\n\n._fileClaimButton_19t6u_35 {\n  position: absolute;\n  top: 8px;\n  right: 8px;\n  z-index: 1;\n  padding: 4px 10px;\n  border: 1px solid rgba(74, 222, 128, 0.45);\n  border-radius: 4px;\n  background: rgba(74, 222, 128, 0.18);\n  color: #6ee7a0;\n  font-family: inherit;\n  font-size: 10px;\n  font-weight: 700;\n  letter-spacing: 0.04em;\n  text-transform: uppercase;\n  cursor: pointer;\n  opacity: 0;\n  transition:\n    opacity 150ms ease,\n    background 150ms ease,\n    border-color 150ms ease,\n    color 150ms ease;\n}\n\n._card_19t6u_1:hover ._fileClaimButton_19t6u_35,\n._card_19t6u_1:focus-within ._fileClaimButton_19t6u_35,\n._fileClaimButton_19t6u_35:focus-visible {\n  opacity: 1;\n}\n\n._fileClaimButton_19t6u_35:hover {\n  background: rgba(74, 222, 128, 0.28);\n  border-color: rgba(74, 222, 128, 0.65);\n  color: #86efac;\n}\n\n._fileClaimButton_19t6u_35:focus-visible {\n  outline: 2px solid #4ade80;\n  outline-offset: 2px;\n}\n\n@media (hover: none), (pointer: coarse) {\n  ._card_19t6u_1 ._fileClaimButton_19t6u_35 {\n    opacity: 1;\n  }\n}\n\n._autoRenewPill_19t6u_82 {\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  flex-shrink: 0;\n  min-width: 18px;\n  height: 18px;\n  padding: 0 6px;\n  border-radius: 4px;\n  border: 1px solid rgba(74, 222, 128, 0.4);\n  background: rgba(74, 222, 128, 0.12);\n  font-family: inherit;\n  font-size: 10px;\n  font-weight: 700;\n  line-height: 1;\n  color: #6ee7a0;\n  cursor: pointer;\n  transition:\n    background 150ms ease,\n    border-color 150ms ease,\n    opacity 150ms ease;\n}\n\n._autoRenewPill_19t6u_82:hover:not(:disabled) {\n  background: rgba(74, 222, 128, 0.22);\n  border-color: rgba(74, 222, 128, 0.6);\n}\n\n._autoRenewPill_19t6u_82:disabled {\n  opacity: 0.6;\n  cursor: wait;\n}\n\n._autoRenewPill_19t6u_82:focus-visible {\n  outline: 2px solid #4ade80;\n  outline-offset: 2px;\n}\n\n._payoutValue_19t6u_120 {\n  color: #6ee7a0;\n}\n\n._timeLeft_19t6u_124 {\n  color: rgba(255, 255, 255, 0.85);\n}\n";
  const insuranceClaimModalStyles = "._dialog_7v3o5_1 {\n  max-width: 400px;\n}\n\n._actions_7v3o5_5 {\n  margin-top: 20px;\n}\n\n._confirmFull_7v3o5_9 {\n  flex: 1;\n  padding: 14px 16px;\n  font-size: 16px;\n}\n\n._autoRenewRow_7v3o5_15 {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  margin: 0 0 12px;\n  cursor: pointer;\n}\n\n._autoRenewText_7v3o5_23 {\n  flex: 1;\n  min-width: 0;\n  font-size: 13px;\n  line-height: 1.45;\n  color: rgba(255, 255, 255, 0.75);\n}\n\n._switch_7v3o5_31 {\n  position: relative;\n  flex-shrink: 0;\n  width: 40px;\n  height: 22px;\n}\n\n._switchInput_7v3o5_38 {\n  position: absolute;\n  opacity: 0;\n  width: 100%;\n  height: 100%;\n  margin: 0;\n  cursor: pointer;\n  z-index: 1;\n}\n\n._switchInput_7v3o5_38:disabled {\n  cursor: not-allowed;\n}\n\n._switchSlider_7v3o5_52 {\n  position: absolute;\n  inset: 0;\n  border-radius: 11px;\n  background: rgba(255, 255, 255, 0.18);\n  border: 1px solid rgba(255, 255, 255, 0.12);\n  transition:\n    background 150ms ease,\n    border-color 150ms ease;\n  pointer-events: none;\n}\n\n._switchSlider_7v3o5_52::before {\n  content: '';\n  position: absolute;\n  top: 2px;\n  left: 2px;\n  width: 16px;\n  height: 16px;\n  border-radius: 50%;\n  background: #fff;\n  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.25);\n  transition: transform 150ms ease;\n}\n\n._switchInput_7v3o5_38:checked + ._switchSlider_7v3o5_52 {\n  background: rgba(74, 222, 128, 0.45);\n  border-color: rgba(74, 222, 128, 0.55);\n}\n\n._switchInput_7v3o5_38:checked + ._switchSlider_7v3o5_52::before {\n  transform: translateX(18px);\n}\n\n._switchInput_7v3o5_38:focus-visible + ._switchSlider_7v3o5_52 {\n  outline: 2px solid #4ade80;\n  outline-offset: 2px;\n}\n\n._switchInput_7v3o5_38:disabled + ._switchSlider_7v3o5_52 {\n  opacity: 0.5;\n}\n";
  const contractTypePickerStyles = "/* Inline variant — dropdown trigger + menu for Buy section */\n._inlineWrap_1fno3_2 {\n  position: relative;\n  display: inline-flex;\n  vertical-align: baseline;\n}\n\n._inlineTrigger_1fno3_8 {\n  display: inline-flex;\n  align-items: center;\n  gap: 8px;\n  margin: 0;\n  padding: 6px 10px;\n  border: 1px solid rgba(112, 139, 219, 0.28);\n  border-radius: 8px;\n  background: #161925;\n  color: rgba(255, 255, 255, 0.92);\n  font-family: inherit;\n  font-size: 12px;\n  font-weight: 600;\n  letter-spacing: 0.05em;\n  text-transform: uppercase;\n  line-height: 1;\n  cursor: pointer;\n  appearance: none;\n  -webkit-appearance: none;\n  transition:\n    border-color 150ms ease,\n    background 150ms ease,\n    color 150ms ease;\n}\n\n._inlineTrigger_1fno3_8:hover:not(:disabled) {\n  border-color: rgba(112, 139, 219, 0.45);\n  background: #1a1d2a;\n}\n\n._inlineTrigger_1fno3_8[aria-expanded='true'] {\n  border-color: rgba(112, 139, 219, 0.5);\n  background: #1a1d2a;\n}\n\n._inlineTrigger_1fno3_8:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._inlineTrigger_1fno3_8:disabled {\n  opacity: 0.55;\n  cursor: not-allowed;\n}\n\n._inlineTriggerLabel_1fno3_53 {\n  display: inline-flex;\n  align-items: center;\n}\n\n._inlineChevron_1fno3_58 {\n  flex-shrink: 0;\n  color: rgba(255, 255, 255, 0.45);\n  transition: transform 150ms ease;\n}\n\n._inlineTrigger_1fno3_8[aria-expanded='true'] ._inlineChevron_1fno3_58 {\n  transform: rotate(180deg);\n  color: rgba(255, 255, 255, 0.72);\n}\n\n._inlineMenu_1fno3_69 {\n  position: absolute;\n  top: calc(100% + 6px);\n  left: 0;\n  z-index: 30;\n  min-width: 168px;\n  margin: 0;\n  padding: 4px;\n  list-style: none;\n  border: 1px solid rgba(112, 139, 219, 0.28);\n  border-radius: 8px;\n  background: #161925;\n  box-shadow: 0 10px 28px rgba(0, 0, 0, 0.5);\n}\n\n._inlineMenuItem_1fno3_84 {\n  margin: 0;\n  padding: 0;\n  list-style: none;\n}\n\n._inlineOption_1fno3_90 {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  width: 100%;\n  margin: 0;\n  padding: 9px 10px;\n  border: none;\n  border-radius: 6px;\n  background: transparent;\n  color: rgba(255, 255, 255, 0.82);\n  font-family: inherit;\n  font-size: 13px;\n  font-weight: 500;\n  text-align: left;\n  letter-spacing: 0.01em;\n  text-transform: none;\n  cursor: pointer;\n  appearance: none;\n  -webkit-appearance: none;\n  transition:\n    background 150ms ease,\n    color 150ms ease;\n}\n\n._inlineOptionIcon_1fno3_115 {\n  flex-shrink: 0;\n  color: rgba(255, 255, 255, 0.55);\n}\n\n._inlineOption_1fno3_90:hover {\n  background: rgba(112, 139, 219, 0.12);\n  color: #fff;\n}\n\n._inlineOption_1fno3_90:hover ._inlineOptionIcon_1fno3_115 {\n  color: rgba(158, 181, 240, 0.95);\n}\n\n._inlineOption_1fno3_90[aria-selected='true'] {\n  background: rgba(112, 139, 219, 0.16);\n  color: #fff;\n}\n\n._inlineOption_1fno3_90[aria-selected='true'] ._inlineOptionIcon_1fno3_115 {\n  color: #9eb5f0;\n}\n\n._inlineOption_1fno3_90:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: -2px;\n}\n\n/* Segment variant — matches ModeSwitch with icons */\n._segment_1fno3_144 {\n  position: relative;\n  display: grid;\n  grid-template-columns: repeat(3, minmax(0, 1fr));\n  gap: 0;\n  width: 100%;\n  min-width: 0;\n  box-sizing: border-box;\n  padding: 4px;\n  border-radius: 10px;\n  background: #12141f;\n  border: 1px solid rgba(112, 139, 219, 0.2);\n  flex-shrink: 0;\n}\n\n._segmentPill_1fno3_159 {\n  position: absolute;\n  top: 4px;\n  left: 4px;\n  width: calc((100% - 8px) / 3);\n  height: calc(100% - 8px);\n  border-radius: 7px;\n  box-shadow: 0 2px 8px rgba(63, 67, 207, 0.35);\n  transition:\n    transform 200ms cubic-bezier(0.4, 0, 0.2, 1),\n    box-shadow 200ms cubic-bezier(0.4, 0, 0.2, 1);\n  pointer-events: none;\n}\n\n._segmentPill_1fno3_159::before,\n._segmentPill_1fno3_159::after {\n  content: '';\n  position: absolute;\n  inset: 0;\n  border-radius: inherit;\n  transition: opacity 200ms cubic-bezier(0.4, 0, 0.2, 1);\n}\n\n._segmentPill_1fno3_159::before {\n  background: linear-gradient(180deg, #708bdb 0%, #3f43cf 100%);\n  opacity: 1;\n}\n\n._segmentPill_1fno3_159::after {\n  background: linear-gradient(#cc7032 0, #b3382c);\n  opacity: 0;\n}\n\n._segmentPillAlert_1fno3_192 {\n  box-shadow: 0 2px 8px rgba(179, 56, 44, 0.35);\n}\n\n._segmentPillAlert_1fno3_192::before {\n  opacity: 0;\n}\n\n._segmentPillAlert_1fno3_192::after {\n  opacity: 1;\n}\n\n._segmentPillHidden_1fno3_204 {\n  opacity: 0;\n}\n\n._segmentPillInstant_1fno3_208 {\n  transition: none;\n}\n\n._segmentButton_1fno3_212 {\n  position: relative;\n  z-index: 1;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  gap: 6px;\n  padding: 10px 8px;\n  min-width: 0;\n  border: none;\n  border-radius: 7px;\n  background: transparent;\n  color: rgba(255, 255, 255, 0.55);\n  font-family: inherit;\n  font-size: 12px;\n  font-weight: 600;\n  line-height: 1.2;\n  cursor: pointer;\n  appearance: none;\n  -webkit-appearance: none;\n  transition: color 150ms ease;\n  white-space: nowrap;\n}\n\n._segmentButtonIcon_1fno3_236 {\n  flex-shrink: 0;\n  color: rgba(255, 255, 255, 0.45);\n  transition: color 150ms ease;\n}\n\n._segmentButton_1fno3_212:hover:not(:disabled) {\n  color: rgba(255, 255, 255, 0.85);\n}\n\n._segmentButton_1fno3_212:hover:not(:disabled) ._segmentButtonIcon_1fno3_236 {\n  color: rgba(255, 255, 255, 0.72);\n}\n\n._segmentButton_1fno3_212[aria-selected='true'] {\n  color: #fff;\n}\n\n._segmentButton_1fno3_212[aria-selected='true'] ._segmentButtonIcon_1fno3_236 {\n  color: rgba(255, 255, 255, 0.92);\n}\n\n._segmentButton_1fno3_212:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 1px;\n}\n\n._segmentButton_1fno3_212:disabled {\n  opacity: 0.55;\n  cursor: not-allowed;\n}\n\n._segmentButtonAlert_1fno3_268:not([aria-selected='true']) {\n  color: #b3382c;\n}\n\n._segmentButtonAlert_1fno3_268:not([aria-selected='true']) ._segmentButtonIcon_1fno3_236 {\n  color: #b3382c;\n}\n\n._segmentButtonAlert_1fno3_268:not([aria-selected='true']):hover:not(:disabled) {\n  color: #cc7032;\n}\n\n._segmentButtonAlert_1fno3_268:not([aria-selected='true']):hover:not(:disabled)\n  ._segmentButtonIcon_1fno3_236 {\n  color: #cc7032;\n}\n\n._segmentOtherWrap_1fno3_285 {\n  position: relative;\n  z-index: 2;\n  display: flex;\n  min-width: 0;\n}\n\n._segmentOtherWrap_1fno3_285 > ._segmentButton_1fno3_212 {\n  flex: 1 1 100%;\n  min-width: 0;\n}\n\n._segmentOtherMenu_1fno3_297 {\n  position: absolute;\n  top: calc(100% + 6px);\n  right: 0;\n  z-index: 40;\n  min-width: 196px;\n  margin: 0;\n  padding: 4px;\n  list-style: none;\n  border: 1px solid rgba(112, 139, 219, 0.28);\n  border-radius: 8px;\n  background: #161925;\n  box-shadow: 0 10px 28px rgba(0, 0, 0, 0.5);\n}\n\n._segmentOtherMenuItem_1fno3_312 {\n  margin: 0;\n  padding: 0;\n  list-style: none;\n}\n\n._segmentOtherOption_1fno3_318 {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  width: 100%;\n  margin: 0;\n  padding: 9px 10px;\n  border: none;\n  border-radius: 6px;\n  background: transparent;\n  color: rgba(255, 255, 255, 0.82);\n  font-family: inherit;\n  font-size: 13px;\n  font-weight: 500;\n  text-align: left;\n  letter-spacing: 0.01em;\n  text-transform: none;\n  cursor: pointer;\n  appearance: none;\n  -webkit-appearance: none;\n  transition:\n    background 150ms ease,\n    color 150ms ease;\n}\n\n._segmentOtherOptionIcon_1fno3_343 {\n  flex-shrink: 0;\n  color: #86efac;\n}\n\n._segmentOtherOption_1fno3_318:hover {\n  background: rgba(74, 222, 128, 0.12);\n  color: #fff;\n}\n\n._segmentOtherOption_1fno3_318[aria-selected='true'] {\n  background: rgba(74, 222, 128, 0.16);\n  color: #fff;\n}\n\n._segmentOtherOption_1fno3_318:focus-visible {\n  outline: 2px solid #6ee7a0;\n  outline-offset: -2px;\n}\n\n._segmentOtherOptionEmbargo_1fno3_363 ._segmentOtherOptionIcon_1fno3_343 {\n  color: #fca5a5;\n}\n\n._segmentOtherOptionEmbargo_1fno3_363:hover {\n  background: rgba(248, 113, 113, 0.12);\n}\n\n._segmentOtherOptionEmbargo_1fno3_363[aria-selected='true'] {\n  background: rgba(248, 113, 113, 0.16);\n}\n\n._segmentOtherOptionEmbargo_1fno3_363:focus-visible {\n  outline-color: #fca5a5;\n}\n\n._segmentOtherOptionGray_1fno3_379 ._segmentOtherOptionIcon_1fno3_343 {\n  color: #e4e4e7;\n}\n\n._segmentOtherOptionGray_1fno3_379:hover {\n  background: rgba(228, 228, 231, 0.12);\n}\n\n._segmentOtherOptionGray_1fno3_379[aria-selected='true'] {\n  background: rgba(228, 228, 231, 0.16);\n}\n\n._segmentOtherOptionGray_1fno3_379:focus-visible {\n  outline-color: #e4e4e7;\n}\n\n/* Overrides the variant text/icon colors — placed last so it wins on equal\n   specificity. A subtype with a matching contract reads as an active alert. */\n._segmentOtherOptionAlert_1fno3_397,\n._segmentOtherOptionAlert_1fno3_397 ._segmentOtherOptionIcon_1fno3_343 {\n  color: #b3382c;\n}\n\n._segmentOtherOptionAlert_1fno3_397:hover {\n  background: rgba(179, 56, 44, 0.12);\n}\n\n._segmentOtherOptionAlert_1fno3_397:hover,\n._segmentOtherOptionAlert_1fno3_397:hover ._segmentOtherOptionIcon_1fno3_343 {\n  color: #cc7032;\n}\n\n._segmentOtherOptionAlert_1fno3_397[aria-selected='true'] {\n  background: rgba(179, 56, 44, 0.16);\n  color: #cc7032;\n}\n\n._segmentOtherChevron_1fno3_416 {\n  flex-shrink: 0;\n  margin-left: 2px;\n  color: rgba(255, 255, 255, 0.45);\n  transition: transform 150ms ease;\n}\n\n._segmentButtonOtherOpen_1fno3_423 ._segmentOtherChevron_1fno3_416 {\n  transform: rotate(180deg);\n  color: rgba(255, 255, 255, 0.72);\n}\n";
  const settingsPanelStyles = "._panel_319qe_1 {\n  display: flex;\n  flex-direction: column;\n  flex: 1;\n  min-height: 0;\n  padding: 4px 2px 12px;\n  overflow-y: auto;\n}\n\n._section_319qe_10 {\n  margin: 0;\n}\n\n._section_319qe_10 + ._section_319qe_10 {\n  margin-top: 28px;\n  padding-top: 24px;\n  border-top: 1px solid rgba(112, 139, 219, 0.18);\n}\n\n._sectionHeading_319qe_20 {\n  margin: 0 0 20px;\n  font-size: 15px;\n  font-weight: 700;\n  color: #fff;\n  letter-spacing: 0.02em;\n}\n\n._fieldLabel_319qe_28 {\n  display: block;\n  margin: 0 0 8px;\n  font-size: 11px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.06em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._alertFields_319qe_38 {\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n}\n\n._alertFields_319qe_38 ._field_319qe_28 {\n  margin: 0;\n}\n\n._alertThresholdTable_319qe_48 {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n}\n\n._alertThresholdHeader_319qe_54 {\n  display: grid;\n  grid-template-columns: minmax(88px, 0.9fr) minmax(0, 1.4fr);\n  gap: 10px;\n  padding: 0 2px;\n  font-size: 10px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.06em;\n  color: rgba(255, 255, 255, 0.32);\n}\n\n._alertThresholdRow_319qe_66 {\n  display: grid;\n  grid-template-columns: minmax(88px, 0.9fr) minmax(0, 1.4fr);\n  gap: 10px;\n  align-items: center;\n}\n\n._alertThresholdLabel_319qe_73 {\n  font-size: 13px;\n  font-weight: 600;\n  color: rgba(255, 255, 255, 0.72);\n}\n\n._alertThresholdInputWrap_319qe_79 {\n  position: relative;\n  display: flex;\n  align-items: center;\n}\n\n._alertThresholdInputWithSuffix_319qe_85 {\n  padding-right: 48px;\n}\n\n._alertThresholdInputSuffix_319qe_89 {\n  position: absolute;\n  right: 11px;\n  top: 50%;\n  transform: translateY(-50%);\n  pointer-events: none;\n  font-size: 12px;\n  font-weight: 700;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._alertThresholdInput_319qe_79 {\n  width: 100%;\n  box-sizing: border-box;\n  padding: 9px 11px;\n  border: 1px solid rgba(112, 139, 219, 0.28);\n  border-radius: 8px;\n  background: #161925;\n  color: rgba(255, 255, 255, 0.92);\n  font-family: inherit;\n  font-size: 14px;\n  font-weight: 500;\n  transition:\n    border-color 150ms ease,\n    background 150ms ease;\n}\n\n._alertThresholdInput_319qe_79::placeholder {\n  color: rgba(255, 255, 255, 0.35);\n}\n\n._alertThresholdInput_319qe_79:hover:not(:disabled) {\n  border-color: rgba(112, 139, 219, 0.45);\n}\n\n._alertThresholdInput_319qe_79:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n  border-color: rgba(112, 139, 219, 0.5);\n}\n\n._alertThresholdInput_319qe_79:disabled {\n  opacity: 0.55;\n  cursor: not-allowed;\n}\n\n._alertInput_319qe_136 {\n  width: 100%;\n  max-width: 72%;\n  box-sizing: border-box;\n  padding: 10px 12px;\n  border: 1px solid rgba(112, 139, 219, 0.28);\n  border-radius: 8px;\n  background: #161925;\n  color: rgba(255, 255, 255, 0.92);\n  font-family: inherit;\n  font-size: 14px;\n  font-weight: 500;\n  transition:\n    border-color 150ms ease,\n    background 150ms ease;\n}\n\n._alertInput_319qe_136::placeholder {\n  color: rgba(255, 255, 255, 0.35);\n}\n\n._alertInput_319qe_136:hover:not(:disabled) {\n  border-color: rgba(112, 139, 219, 0.45);\n}\n\n._alertInput_319qe_136:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n  border-color: rgba(112, 139, 219, 0.5);\n}\n\n._alertInput_319qe_136:disabled {\n  opacity: 0.55;\n  cursor: not-allowed;\n}\n\n._alertInputError_319qe_172 {\n  border-color: rgba(220, 80, 80, 0.55);\n}\n\n._alertHint_319qe_176 {\n  margin: 8px 0 0;\n  font-size: 12px;\n  line-height: 1.45;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._alertError_319qe_183 {\n  margin: 8px 0 0;\n  font-size: 12px;\n  line-height: 1.45;\n  color: #f5a0a0;\n}\n\n._alertConfirm_319qe_190 {\n  align-self: flex-start;\n  width: 100%;\n  max-width: 72%;\n  padding: 10px 14px;\n  border: none;\n  border-radius: 8px;\n  background: linear-gradient(180deg, #708bdb 0%, #3f43cf 100%);\n  color: #fff;\n  font-family: inherit;\n  font-size: 13px;\n  font-weight: 600;\n  cursor: pointer;\n  white-space: nowrap;\n  transition: filter 150ms ease;\n}\n\n._alertConfirm_319qe_190:hover:not(:disabled) {\n  filter: brightness(1.08);\n}\n\n._alertConfirm_319qe_190:disabled {\n  opacity: 0.5;\n  cursor: not-allowed;\n  filter: none;\n}\n\n._alertConfirm_319qe_190:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._volumeRow_319qe_222 {\n  margin: 0;\n}\n\n._volumeControl_319qe_226 {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  max-width: 72%;\n}\n\n._volumeSlider_319qe_233 {\n  flex: 1;\n  min-width: 0;\n  height: 6px;\n  margin: 0;\n  accent-color: #708bdb;\n  cursor: pointer;\n}\n\n._volumeSlider_319qe_233:disabled {\n  opacity: 0.55;\n  cursor: not-allowed;\n}\n\n._volumeSlider_319qe_233:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._volumeValue_319qe_252 {\n  flex-shrink: 0;\n  min-width: 2.5rem;\n  font-size: 13px;\n  font-weight: 600;\n  font-variant-numeric: tabular-nums;\n  color: rgba(255, 255, 255, 0.75);\n  text-align: right;\n}\n\n._fieldList_319qe_262 {\n  margin: 0;\n  padding: 0;\n  display: flex;\n  flex-direction: column;\n  gap: 16px;\n}\n\n._field_319qe_28 {\n  margin: 0;\n}\n\n._field_319qe_28 dt {\n  margin: 0 0 6px;\n  font-size: 11px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.06em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._field_319qe_28 dd {\n  margin: 0;\n  font-size: 14px;\n  font-weight: 500;\n  color: rgba(255, 255, 255, 0.92);\n  word-break: break-word;\n}\n\n._mono_319qe_291 {\n  font-variant-numeric: tabular-nums;\n  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n}\n\n._apiKeyRow_319qe_296 {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n}\n\n._apiKeyValue_319qe_302 {\n  flex: 1;\n  min-width: 0;\n  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n  font-size: 13px;\n  color: rgba(255, 255, 255, 0.8);\n}\n\n._eyeButton_319qe_310 {\n  flex-shrink: 0;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 32px;\n  height: 32px;\n  padding: 0;\n  border: 1px solid rgba(112, 139, 219, 0.28);\n  border-radius: 8px;\n  background: #161925;\n  color: rgba(255, 255, 255, 0.65);\n  cursor: pointer;\n  transition:\n    color 150ms ease,\n    border-color 150ms ease,\n    background 150ms ease;\n}\n\n._eyeButton_319qe_310:hover {\n  color: #fff;\n  border-color: rgba(112, 139, 219, 0.5);\n  background: #1c2030;\n}\n\n._eyeButton_319qe_310:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._actions_319qe_340 {\n  display: flex;\n  flex-direction: column;\n  gap: 10px;\n  margin-top: 28px;\n  padding-top: 20px;\n  border-top: 1px solid rgba(112, 139, 219, 0.18);\n}\n\n._logoutButton_319qe_349,\n._deleteAccountButton_319qe_350,\n._connectButton_319qe_351 {\n  width: 100%;\n  padding: 12px 16px;\n  border: none;\n  border-radius: 10px;\n  font-family: inherit;\n  font-size: 14px;\n  font-weight: 600;\n  cursor: pointer;\n  transition:\n    background 150ms ease,\n    opacity 150ms ease;\n}\n\n._logoutButton_319qe_349 {\n  background: rgba(220, 80, 80, 0.18);\n  color: #f5a0a0;\n  border: 1px solid rgba(220, 80, 80, 0.35);\n}\n\n._logoutButton_319qe_349:hover:not(:disabled) {\n  background: rgba(220, 80, 80, 0.28);\n  color: #ffc8c8;\n}\n\n._logoutButton_319qe_349:disabled {\n  opacity: 0.6;\n  cursor: not-allowed;\n}\n\n._deleteAccountButton_319qe_350 {\n  background: transparent;\n  color: rgba(245, 160, 160, 0.85);\n  border: 1px solid rgba(220, 80, 80, 0.35);\n}\n\n._deleteAccountButton_319qe_350:hover:not(:disabled) {\n  background: rgba(220, 80, 80, 0.12);\n  color: #ffc8c8;\n  border-color: rgba(220, 80, 80, 0.5);\n}\n\n._deleteAccountButton_319qe_350:disabled {\n  opacity: 0.6;\n  cursor: not-allowed;\n}\n\n._connectButton_319qe_351 {\n  background: linear-gradient(180deg, #708bdb 0%, #3f43cf 100%);\n  color: #fff;\n  box-shadow: 0 2px 8px rgba(63, 67, 207, 0.35);\n}\n\n._viewArchiveButton_319qe_404 {\n  width: 100%;\n  padding: 12px 16px;\n  border: 1px solid rgba(112, 139, 219, 0.4);\n  border-radius: 10px;\n  background: rgba(112, 139, 219, 0.12);\n  color: #c2cdf2;\n  font-family: inherit;\n  font-size: 14px;\n  font-weight: 600;\n  cursor: pointer;\n  transition:\n    background 150ms ease,\n    color 150ms ease;\n}\n\n._viewArchiveButton_319qe_404:hover {\n  background: rgba(112, 139, 219, 0.2);\n  color: #fff;\n}\n\n._viewArchiveButton_319qe_404:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._connectButton_319qe_351:hover {\n  filter: brightness(1.06);\n}\n\n._logoutButton_319qe_349:focus-visible,\n._deleteAccountButton_319qe_350:focus-visible,\n._connectButton_319qe_351:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._legalFooter_319qe_441 {\n  display: flex;\n  flex-wrap: wrap;\n  align-items: center;\n  gap: 6px;\n  margin-top: 16px;\n  font-size: 12px;\n}\n\n._versionLabel_319qe_450 {\n  margin-left: auto;\n  color: rgba(200, 210, 240, 0.45);\n  font-variant-numeric: tabular-nums;\n  user-select: all;\n}\n\n._legalLink_319qe_457 {\n  color: rgba(200, 210, 240, 0.75);\n  text-decoration: none;\n}\n\n._legalLink_319qe_457:hover {\n  color: #fff;\n  text-decoration: underline;\n}\n\n._legalLink_319qe_457:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n  border-radius: 2px;\n}\n\n._legalSep_319qe_473 {\n  color: rgba(200, 210, 240, 0.4);\n}\n\n/* Alert sub-section (collapsible groups inside the Alert section). */\n._alertGroup_319qe_478 {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n}\n\n._alertGroupHeader_319qe_484 {\n  display: flex;\n  align-items: center;\n  justify-content: space-between;\n  gap: 8px;\n  width: 100%;\n  padding: 6px 2px;\n  border: none;\n  background: transparent;\n  color: rgba(255, 255, 255, 0.72);\n  font-family: inherit;\n  font-size: 11px;\n  font-weight: 700;\n  text-transform: uppercase;\n  letter-spacing: 0.06em;\n  cursor: pointer;\n  appearance: none;\n  -webkit-appearance: none;\n}\n\n._alertGroupHeader_319qe_484:hover {\n  color: #fff;\n}\n\n._alertGroupHeader_319qe_484:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n  border-radius: 4px;\n}\n\n._alertGroupChevron_319qe_514 {\n  flex-shrink: 0;\n  color: rgba(255, 255, 255, 0.5);\n  transition: transform 150ms ease;\n}\n\n._alertGroupChevronOpen_319qe_520 {\n  transform: rotate(90deg);\n}\n\n._alertGroupBody_319qe_524 {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n}\n\n._alertGroupCollapsedBadges_319qe_530 {\n  display: flex;\n  align-items: center;\n  gap: 6px;\n}\n\n._alertCollapsedBadge_319qe_536 {\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  width: 26px;\n  height: 26px;\n  padding: 0;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  border-radius: 6px;\n  background: rgba(112, 139, 219, 0.12);\n  color: #9eb5f0;\n  cursor: pointer;\n  appearance: none;\n  -webkit-appearance: none;\n  transition:\n    background 150ms ease,\n    border-color 150ms ease,\n    color 150ms ease;\n}\n\n._alertCollapsedBadge_319qe_536:hover {\n  border-color: rgba(112, 139, 219, 0.6);\n  background: rgba(112, 139, 219, 0.2);\n  color: #fff;\n}\n\n._alertCollapsedBadge_319qe_536:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._alertCollapsedBadgeActive_319qe_567 {\n  border-color: rgba(232, 164, 58, 0.55);\n  background: rgba(232, 164, 58, 0.18);\n  color: #f0c050;\n}\n\n._alertCollapsedBadgeActive_319qe_567:hover {\n  border-color: rgba(232, 164, 58, 0.85);\n  background: rgba(232, 164, 58, 0.28);\n  color: #ffd470;\n}\n";
  const animatedListStyles = ".scroll-list-container {\n  position: relative;\n  width: 100%;\n  flex: 1;\n  min-height: 0;\n}\n\n.scroll-list {\n  height: 100%;\n  max-height: 100%;\n  overflow-y: auto;\n  padding: 4px 4px 8px;\n}\n\n.scroll-list::-webkit-scrollbar {\n  width: 8px;\n}\n\n.scroll-list::-webkit-scrollbar-track {\n  background: #12141f;\n}\n\n.scroll-list::-webkit-scrollbar-thumb {\n  background: #3a3f5c;\n  border-radius: 4px;\n}\n\n.no-scrollbar::-webkit-scrollbar {\n  display: none;\n}\n\n.no-scrollbar {\n  -ms-overflow-style: none;\n  scrollbar-width: none;\n}\n\n.item {\n  padding: 14px 16px;\n  background-color: #252838;\n  border: 1px solid rgba(112, 139, 219, 0.12);\n  border-radius: 8px;\n}\n\n.item.selected {\n  border-color: rgba(112, 139, 219, 0.45);\n  background-color: #2e3348;\n  box-shadow: 0 0 0 1px rgba(112, 139, 219, 0.2);\n}\n\n.item-text {\n  color: #e8eaf0;\n  margin: 0;\n}\n\n.top-gradient {\n  position: absolute;\n  top: 0;\n  left: 0;\n  right: 0;\n  height: 50px;\n  background: linear-gradient(to bottom, #1a1d2e, transparent);\n  pointer-events: none;\n  transition: opacity 0.3s ease;\n}\n\n.bottom-gradient {\n  position: absolute;\n  bottom: 0;\n  left: 0;\n  right: 0;\n  height: 100px;\n  background: linear-gradient(to top, #1a1d2e, transparent);\n  pointer-events: none;\n  transition: opacity 0.3s ease;\n}\n";
  const inProgressModalStyles = "._list_1k1dk_1 {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n  margin: 0;\n  padding: 0;\n  list-style: none;\n}\n\n._row_1k1dk_10 {\n  display: grid;\n  grid-template-columns: 1fr auto auto;\n  align-items: center;\n  gap: 16px;\n  padding: 12px 14px;\n  border-radius: 8px;\n  border: 1px solid rgba(232, 164, 58, 0.35);\n  background: rgba(232, 164, 58, 0.08);\n}\n\n._party_1k1dk_21 {\n  display: flex;\n  flex-direction: column;\n  gap: 2px;\n  min-width: 0;\n}\n\n._partyLabel_1k1dk_28 {\n  font-size: 11px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._partyLink_1k1dk_36 {\n  font-size: 14px;\n  font-weight: 700;\n  color: #c5d4f7;\n  text-decoration: none;\n  font-variant-numeric: tabular-nums;\n}\n\n._partyLink_1k1dk_36:hover {\n  color: #fff;\n  text-decoration: underline;\n}\n\n._quantity_1k1dk_49 {\n  display: flex;\n  flex-direction: column;\n  align-items: flex-end;\n  gap: 2px;\n  flex-shrink: 0;\n}\n\n._quantityLabel_1k1dk_57 {\n  font-size: 10px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._quantityValue_1k1dk_65 {\n  font-size: 14px;\n  font-weight: 700;\n  color: #fff;\n  font-variant-numeric: tabular-nums;\n}\n\n._timer_1k1dk_72 {\n  display: flex;\n  flex-direction: column;\n  align-items: flex-end;\n  gap: 2px;\n  flex-shrink: 0;\n}\n\n._timerLabel_1k1dk_80 {\n  font-size: 10px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._timerValue_1k1dk_88 {\n  font-size: 14px;\n  font-weight: 700;\n  color: #e8a43a;\n  font-variant-numeric: tabular-nums;\n}\n\n._timerExpired_1k1dk_95 {\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._empty_1k1dk_99 {\n  margin: 0;\n  padding: 16px;\n  text-align: center;\n  font-size: 13px;\n  color: rgba(255, 255, 255, 0.5);\n}\n";
  const buyerOrderProgressModalStyles = "._dialog_1azzx_1 {\n  width: min(480px, calc(100vw - 32px));\n  max-width: 480px;\n  display: flex;\n  flex-direction: column;\n  gap: 16px;\n}\n\n._progressSection_1azzx_9 {\n  display: flex;\n  flex-direction: column;\n  gap: 0;\n}\n\n._progressTrack_1azzx_15 {\n  position: relative;\n  height: 32px;\n  border-radius: 8px;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  background: #12141f;\n  overflow: hidden;\n  cursor: default;\n}\n\n._progressFill_1azzx_25 {\n  position: absolute;\n  top: 0;\n  left: 0;\n  bottom: 0;\n  border-radius: 7px;\n  background: linear-gradient(90deg, #5a74c4 0%, #708bdb 50%, #9eb5f0 100%);\n  transition: width 200ms ease;\n  z-index: 0;\n}\n\n._progressBarLabel_1azzx_36 {\n  position: absolute;\n  inset: 0;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  z-index: 1;\n  font-size: 12px;\n  font-weight: 700;\n  font-variant-numeric: tabular-nums;\n  letter-spacing: 0.02em;\n  color: #fff;\n  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.65);\n  pointer-events: none;\n  user-select: none;\n}\n\n._contributorsSection_1azzx_53 {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n}\n\n._contributorsHeader_1azzx_59 {\n  display: grid;\n  grid-template-columns: 1fr auto;\n  gap: 12px;\n  padding: 0 4px;\n}\n\n._sortButton_1azzx_66 {\n  display: inline-flex;\n  align-items: center;\n  gap: 4px;\n  margin: 0;\n  padding: 0;\n  border: none;\n  background: transparent;\n  font-family: inherit;\n  font-size: 10px;\n  font-weight: 700;\n  text-transform: uppercase;\n  letter-spacing: 0.05em;\n  color: rgba(255, 255, 255, 0.45);\n  cursor: pointer;\n}\n\n._sortButton_1azzx_66:hover,\n._sortButton_1azzx_66:focus-visible {\n  color: rgba(255, 255, 255, 0.8);\n}\n\n._sortButtonActive_1azzx_88 {\n  color: #9eb5f0;\n}\n\n._sortButtonRight_1azzx_92 {\n  justify-self: end;\n}\n\n._sortIndicator_1azzx_96 {\n  font-size: 8px;\n  line-height: 1;\n}\n\n._contributorsList_1azzx_101 {\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n  margin: 0;\n  padding: 0;\n  list-style: none;\n  max-height: 240px;\n  overflow-y: auto;\n}\n\n._contributorRow_1azzx_112 {\n  display: grid;\n  grid-template-columns: 1fr auto;\n  align-items: center;\n  gap: 16px;\n  padding: 10px 12px;\n  border-radius: 8px;\n  border: 1px solid rgba(112, 139, 219, 0.25);\n  background: rgba(112, 139, 219, 0.08);\n}\n\n._sellerLink_1azzx_123 {\n  font-size: 14px;\n  font-weight: 700;\n  color: #c5d4f7;\n  text-decoration: none;\n  font-variant-numeric: tabular-nums;\n}\n\n._sellerLink_1azzx_123:hover,\n._sellerLink_1azzx_123:focus-visible {\n  color: #fff;\n  text-decoration: underline;\n}\n\n._attacksValue_1azzx_137 {\n  font-size: 14px;\n  font-weight: 700;\n  color: #fff;\n  font-variant-numeric: tabular-nums;\n  text-align: right;\n  min-width: 2ch;\n}\n\n._empty_1azzx_146 {\n  margin: 0;\n  padding: 20px 12px;\n  text-align: center;\n  font-size: 13px;\n  color: rgba(255, 255, 255, 0.5);\n  border-radius: 8px;\n  border: 1px dashed rgba(255, 255, 255, 0.12);\n  background: rgba(0, 0, 0, 0.15);\n}\n";
  const referralsModalStyles = "._codeRow_1b6f7_1 {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  flex-wrap: wrap;\n  margin-bottom: 16px;\n  padding: 12px 14px;\n  border-radius: 8px;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  background: rgba(112, 139, 219, 0.08);\n}\n\n._referredBy_1b6f7_13 {\n  margin: -8px 0 16px;\n  font-size: 13px;\n  color: rgba(255, 255, 255, 0.75);\n}\n\n._enterCodeBlock_1b6f7_19 {\n  margin-bottom: 16px;\n  padding: 12px 14px;\n  border-radius: 8px;\n  border: 1px solid rgba(232, 164, 58, 0.35);\n  background: rgba(232, 164, 58, 0.08);\n}\n\n._enterCodeHint_1b6f7_27 {\n  margin: 0 0 10px;\n  font-size: 12px;\n  color: rgba(255, 255, 255, 0.55);\n  line-height: 1.45;\n}\n\n._enterCodeRow_1b6f7_34 {\n  display: flex;\n  gap: 8px;\n}\n\n._enterCodeInput_1b6f7_39 {\n  flex: 1;\n  min-width: 0;\n  padding: 10px 12px;\n  border-radius: 8px;\n  border: 1px solid rgba(112, 139, 219, 0.28);\n  background: #161925;\n  color: #fff;\n  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n  font-size: 14px;\n  letter-spacing: 0.06em;\n}\n\n._enterCodeInputError_1b6f7_52 {\n  border-color: rgba(220, 80, 80, 0.65);\n}\n\n._enterCodeApply_1b6f7_56 {\n  flex-shrink: 0;\n  padding: 10px 14px;\n  border-radius: 8px;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  background: rgba(112, 139, 219, 0.12);\n  color: #c5d4f7;\n  font-family: inherit;\n  font-size: 13px;\n  font-weight: 600;\n  cursor: pointer;\n}\n\n._enterCodeApply_1b6f7_56:hover:not(:disabled) {\n  background: rgba(112, 139, 219, 0.22);\n  color: #fff;\n}\n\n._enterCodeApply_1b6f7_56:disabled {\n  opacity: 0.55;\n  cursor: not-allowed;\n}\n\n._enterCodeError_1b6f7_79 {\n  margin: 8px 0 0;\n  font-size: 12px;\n  color: #f5a0a0;\n}\n\n._enterCodeSuccess_1b6f7_85 {\n  margin: 8px 0 0;\n  font-size: 12px;\n  color: #6dd4a0;\n}\n\n._codeLabel_1b6f7_91 {\n  font-size: 11px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.45);\n  width: 100%;\n}\n\n._codeValue_1b6f7_100 {\n  flex: 1;\n  min-width: 0;\n  font-size: 18px;\n  font-weight: 700;\n  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;\n  letter-spacing: 0.08em;\n  color: #fff;\n}\n\n._stats_1b6f7_110 {\n  display: grid;\n  grid-template-columns: repeat(3, 1fr);\n  gap: 10px;\n  margin: 0 0 16px;\n  padding: 0;\n}\n\n._stat_1b6f7_110 {\n  margin: 0;\n  padding: 10px 12px;\n  border-radius: 8px;\n  border: 1px solid rgba(255, 255, 255, 0.08);\n  background: rgba(255, 255, 255, 0.04);\n}\n\n._stat_1b6f7_110 dt {\n  margin: 0 0 4px;\n  font-size: 10px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._stat_1b6f7_110 dd {\n  margin: 0;\n  font-size: 14px;\n  font-weight: 700;\n  color: #fff;\n  font-variant-numeric: tabular-nums;\n}\n\n._list_1b6f7_143 {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n  margin: 0;\n  padding: 0;\n  list-style: none;\n  max-height: 280px;\n  overflow-y: auto;\n}\n\n._row_1b6f7_154 {\n  display: grid;\n  grid-template-columns: 1fr auto auto;\n  align-items: center;\n  gap: 12px;\n  padding: 12px 14px;\n  border-radius: 8px;\n  border: 1px solid rgba(232, 164, 58, 0.35);\n  background: rgba(232, 164, 58, 0.08);\n}\n\n._party_1b6f7_165 {\n  display: flex;\n  flex-direction: column;\n  gap: 2px;\n  min-width: 0;\n}\n\n._partyLabel_1b6f7_172 {\n  font-size: 11px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._partyLink_1b6f7_180 {\n  font-size: 14px;\n  font-weight: 700;\n  color: #c5d4f7;\n  text-decoration: none;\n  font-variant-numeric: tabular-nums;\n}\n\n._partyLink_1b6f7_180:hover {\n  color: #fff;\n  text-decoration: underline;\n}\n\n._progress_1b6f7_193 {\n  display: flex;\n  flex-direction: column;\n  align-items: flex-end;\n  gap: 2px;\n  flex-shrink: 0;\n}\n\n._progressLabel_1b6f7_201 {\n  font-size: 10px;\n  font-weight: 600;\n  text-transform: uppercase;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._progressValue_1b6f7_209 {\n  font-size: 12px;\n  font-weight: 600;\n  color: rgba(255, 255, 255, 0.85);\n  font-variant-numeric: tabular-nums;\n  text-align: right;\n}\n\n._status_1b6f7_217 {\n  flex-shrink: 0;\n  font-size: 11px;\n  font-weight: 700;\n  text-transform: uppercase;\n  letter-spacing: 0.04em;\n  padding: 4px 8px;\n  border-radius: 999px;\n}\n\n._status_pending_1b6f7_227 {\n  color: #e8a43a;\n  background: rgba(232, 164, 58, 0.15);\n}\n\n._status_qualified_1b6f7_232 {\n  color: #708bdb;\n  background: rgba(112, 139, 219, 0.15);\n}\n\n._status_paid_1b6f7_237 {\n  color: #6dd4a0;\n  background: rgba(109, 212, 160, 0.15);\n}\n\n._empty_1b6f7_242 {\n  margin: 0;\n  padding: 16px;\n  text-align: center;\n  font-size: 13px;\n  color: rgba(255, 255, 255, 0.5);\n}\n";
  const productivityBoostOrderModalStyles = "._dialog_wjgpw_1 {\n  width: 100%;\n  max-width: 420px;\n  height: 520px;\n  max-height: min(90vh, 520px);\n  display: flex;\n  flex-direction: column;\n  overflow: hidden;\n}\n\n._block_wjgpw_11 {\n  display: flex;\n  flex-direction: column;\n  gap: 12px;\n  margin: 0;\n  padding: 0;\n  border: none;\n  height: 100%;\n}\n\n._fieldHint_wjgpw_21 {\n  margin: 6px 0 0;\n  font-size: 12px;\n  color: rgba(255, 255, 255, 0.4);\n  line-height: 1.45;\n}\n\n._factionRow_wjgpw_28 {\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n  margin-top: 14px;\n  padding-top: 14px;\n  border-top: 1px solid rgba(255, 255, 255, 0.08);\n}\n\n._factionButton_wjgpw_37 {\n  align-self: flex-start;\n  padding: 8px 14px;\n  border-radius: 8px;\n  border: 1px dashed rgba(228, 228, 231, 0.4);\n  background: rgba(228, 228, 231, 0.06);\n  color: #e4e4e7;\n  font-family: inherit;\n  font-size: 13px;\n  font-weight: 600;\n  cursor: pointer;\n  appearance: none;\n  -webkit-appearance: none;\n  transition:\n    background 150ms ease,\n    border-color 150ms ease;\n}\n\n._factionButton_wjgpw_37:hover {\n  border-color: rgba(228, 228, 231, 0.7);\n  background: rgba(228, 228, 231, 0.12);\n}\n\n._factionButton_wjgpw_37:focus-visible {\n  outline: 2px solid #e4e4e7;\n  outline-offset: 2px;\n}\n\n._factionToggle_wjgpw_65 {\n  align-self: flex-start;\n  margin-top: 2px;\n  padding: 0;\n  border: none;\n  background: transparent;\n  color: rgba(255, 255, 255, 0.5);\n  font-family: inherit;\n  font-size: 12px;\n  font-weight: 600;\n  text-decoration: underline;\n  text-underline-offset: 2px;\n  cursor: pointer;\n}\n\n._factionToggle_wjgpw_65:hover {\n  color: rgba(255, 255, 255, 0.8);\n}\n\n._factionToggle_wjgpw_65:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n  border-radius: 2px;\n}\n\n._reviewHint_wjgpw_90 {\n  margin: 0;\n  font-size: 13px;\n  line-height: 1.5;\n  color: rgba(255, 255, 255, 0.55);\n}\n\n._priceLabel_wjgpw_97 {\n  display: flex;\n  align-items: baseline;\n  justify-content: space-between;\n  flex-wrap: nowrap;\n  width: 100%;\n  gap: 8px;\n}\n\n._priceLabelLeft_wjgpw_106 {\n  display: flex;\n  align-items: baseline;\n  flex-wrap: wrap;\n  gap: 6px;\n  min-width: 0;\n}\n\n._priceLabelRecommended_wjgpw_114 {\n  flex-shrink: 0;\n  margin-left: auto;\n  font-size: 12px;\n  font-weight: 600;\n  text-transform: none;\n  letter-spacing: normal;\n  color: rgba(255, 255, 255, 0.45);\n  font-variant-numeric: tabular-nums;\n  white-space: nowrap;\n}\n\n._priceLabelRecommendedWarning_wjgpw_126 {\n  flex-shrink: 0;\n  margin-left: auto;\n  font-size: 12px;\n  font-weight: 600;\n  text-transform: none;\n  letter-spacing: normal;\n  font-variant-numeric: tabular-nums;\n  white-space: nowrap;\n  color: #f87171;\n}\n";
  const productivityBoostCompanyLinkStyles = "a._link_c5pde_1,\n._link_c5pde_1 {\n  color: #6ee7a0 !important;\n  font-weight: 600 !important;\n  text-decoration: underline !important;\n  text-decoration-style: dotted !important;\n  text-decoration-color: #6ee7a0 !important;\n  text-underline-offset: 2px !important;\n}\n\na._link_c5pde_1:hover,\na._link_c5pde_1:focus-visible,\n._link_c5pde_1:hover,\n._link_c5pde_1:focus-visible {\n  color: #86efac !important;\n  text-decoration-style: solid !important;\n  text-decoration-color: #86efac !important;\n}\n\na._link_c5pde_1:focus-visible,\n._link_c5pde_1:focus-visible {\n  outline: 2px solid #6ee7a0;\n  outline-offset: 2px;\n  border-radius: 2px;\n}\n";
  const activeProductivityBoostCardStyles = "._badge_igz09_1 {\n  background: transparent;\n  color: #86efac;\n}\n\n._payoutValue_igz09_6 {\n  display: inline;\n}\n\n._valueGreen_igz09_10 {\n  color: #6ee7a0;\n}\n\n._valueRed_igz09_14 {\n  color: #fca5a5;\n}\n\n._valueGray_igz09_18 {\n  color: #e4e4e7;\n}\n";
  const embargoTargetLinkStyles = "a._link_1msbj_1,\n._link_1msbj_1 {\n  color: #fca5a5 !important;\n  font-weight: 600 !important;\n  text-decoration: underline !important;\n  text-decoration-style: dotted !important;\n  text-decoration-color: #fca5a5 !important;\n  text-underline-offset: 2px !important;\n}\n\na._link_1msbj_1:hover,\na._link_1msbj_1:focus-visible,\n._link_1msbj_1:hover,\n._link_1msbj_1:focus-visible {\n  color: #f87171 !important;\n  text-decoration-style: solid !important;\n  text-decoration-color: #f87171 !important;\n}\n\na._link_1msbj_1:focus-visible,\n._link_1msbj_1:focus-visible {\n  outline: 2px solid #fca5a5;\n  outline-offset: 2px;\n  border-radius: 2px;\n}\n";
  const flightDelayTargetLinkStyles = "a._link_1msbj_1,\n._link_1msbj_1 {\n  color: #fca5a5 !important;\n  font-weight: 600 !important;\n  text-decoration: underline !important;\n  text-decoration-style: dotted !important;\n  text-decoration-color: #fca5a5 !important;\n  text-underline-offset: 2px !important;\n}\n\na._link_1msbj_1:hover,\na._link_1msbj_1:focus-visible,\n._link_1msbj_1:hover,\n._link_1msbj_1:focus-visible {\n  color: #f87171 !important;\n  text-decoration-style: solid !important;\n  text-decoration-color: #f87171 !important;\n}\n\na._link_1msbj_1:focus-visible,\n._link_1msbj_1:focus-visible {\n  outline: 2px solid #fca5a5;\n  outline-offset: 2px;\n  border-radius: 2px;\n}\n";
  const simpleServiceTargetLinkStyles = "a._link_18ay8_1,\n._link_18ay8_1 {\n  color: #e4e4e7 !important;\n  font-weight: 600 !important;\n  text-decoration: underline !important;\n  text-decoration-style: dotted !important;\n  text-decoration-color: #e4e4e7 !important;\n  text-underline-offset: 2px !important;\n}\n\na._link_18ay8_1:hover,\na._link_18ay8_1:focus-visible,\n._link_18ay8_1:hover,\n._link_18ay8_1:focus-visible {\n  color: #fafafa !important;\n  text-decoration-style: solid !important;\n  text-decoration-color: #fafafa !important;\n}\n\na._link_18ay8_1:focus-visible,\n._link_18ay8_1:focus-visible {\n  outline: 2px solid #e4e4e7;\n  outline-offset: 2px;\n  border-radius: 2px;\n}\n";
  const referencesReportModalStyles = `._titleRow_4kuie_1 {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 10px;
}

._copyButton_4kuie_8 {
  flex-shrink: 0;
  padding: 4px 9px;
  border-radius: 5px;
  border: 1px solid rgba(112, 139, 219, 0.4);
  background: rgba(112, 139, 219, 0.12);
  color: #c2cdf2;
  font-family: inherit;
  font-size: 11px;
  font-weight: 600;
  cursor: pointer;
  white-space: nowrap;
  transition:
    background 150ms ease,
    color 150ms ease;
}

._copyButton_4kuie_8:hover {
  background: rgba(112, 139, 219, 0.22);
  color: #fff;
}

/* Yellow "Archive" sized to its label; the Close button stays full-width. */
._archiveButton_4kuie_31 {
  background: linear-gradient(180deg, #e6b73c 0%, #c8941a 100%);
  color: #fff;
}

._archiveButton_4kuie_31:hover {
  filter: brightness(1.08);
}

/* Cap the whole dialog to the viewport so a long report can't overflow the
   screen on mobile (the centered overlay can't scroll). The body flexes to
   absorb the remaining space and scrolls internally. */
._reportDialog_4kuie_43 {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  /* vh first as a fallback; dvh overrides where supported. Without the vh
     fallback, an engine that doesn't know dvh drops the cap entirely and the
     dialog overflows the (non-scrollable, centered) overlay top and bottom. */
  max-height: calc(100vh - 40px);
  max-height: calc(100dvh - 40px);
}

._body_4kuie_54 {
  flex: 1 1 auto;
  min-height: 0;
  max-height: 50vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 14px;
  margin: 4px 0 8px;
  padding-right: 4px;
}

._section_4kuie_66 {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

._heading_4kuie_72 {
  margin: 0 0 6px;
  font-size: 11px;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  color: #e4e4e7;
}

._row_4kuie_81 {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  gap: 10px;
  padding: 5px 8px;
  border-radius: 6px;
  font-size: 12.5px;
}

._row_4kuie_81:nth-child(odd) {
  background: rgba(255, 255, 255, 0.04);
}

._name_4kuie_95 {
  color: rgba(255, 255, 255, 0.9);
  font-weight: 600;
  min-width: 0;
  overflow-wrap: anywhere;
}

._listerId_4kuie_102 {
  color: rgba(255, 255, 255, 0.4);
  font-weight: 400;
  font-variant-numeric: tabular-nums;
}

._dates_4kuie_108 {
  flex-shrink: 0;
  display: inline-flex;
  align-items: baseline;
  gap: 8px;
  color: rgba(255, 255, 255, 0.5);
  font-variant-numeric: tabular-nums;
  white-space: nowrap;
}

._days_4kuie_118 {
  flex-shrink: 0;
  padding: 1px 6px;
  border-radius: 4px;
  background: rgba(112, 139, 219, 0.16);
  color: #9eb5f0;
  font-size: 11px;
  font-weight: 600;
}

._empty_4kuie_128 {
  margin: 0;
  font-size: 12.5px;
  color: rgba(255, 255, 255, 0.45);
}

._meta_4kuie_134 {
  margin: 0 0 4px;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.5);
}
`;
  const alertBellPopoverStyles = "._wrap_1vlbk_1 {\n  position: relative;\n  display: inline-flex;\n  flex-shrink: 0;\n}\n\n._bell_1vlbk_7 {\n  position: relative;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  width: 34px;\n  height: 34px;\n  margin: 0;\n  padding: 0;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  border-radius: 8px;\n  background: rgba(112, 139, 219, 0.1);\n  color: rgba(158, 181, 240, 0.85);\n  cursor: pointer;\n  appearance: none;\n  -webkit-appearance: none;\n  transition:\n    color 150ms ease,\n    border-color 150ms ease,\n    background 150ms ease;\n}\n\n._bell_1vlbk_7:hover:not(:disabled) {\n  color: #c8d8ff;\n  border-color: rgba(112, 139, 219, 0.55);\n  background: rgba(112, 139, 219, 0.18);\n}\n\n._bell_1vlbk_7:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._bell_1vlbk_7:disabled {\n  opacity: 0.5;\n  cursor: not-allowed;\n}\n\n._bellActive_1vlbk_45 {\n  border-color: rgba(232, 164, 58, 0.55);\n  background: rgba(232, 164, 58, 0.18);\n  color: #f0c050;\n}\n\n._matchBadge_1vlbk_51 {\n  position: absolute;\n  top: -6px;\n  right: -6px;\n  min-width: 16px;\n  height: 16px;\n  padding: 0 3px;\n  box-sizing: border-box;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  border-radius: 8px;\n  background: linear-gradient(#cc7032 0, #b3382c);\n  color: #fff;\n  font-size: 10px;\n  font-weight: 700;\n  line-height: 1;\n  font-variant-numeric: tabular-nums;\n  box-shadow: 0 0 0 2px #1a1d2e;\n  pointer-events: none;\n}\n\n._bellActive_1vlbk_45:hover:not(:disabled) {\n  border-color: rgba(232, 164, 58, 0.85);\n  background: rgba(232, 164, 58, 0.28);\n  color: #ffd470;\n}\n\n._popover_1vlbk_79 {\n  position: absolute;\n  top: calc(100% + 8px);\n  right: 0;\n  z-index: 50;\n  width: 248px;\n  max-width: 80vw;\n  box-sizing: border-box;\n  display: flex;\n  flex-direction: column;\n  gap: 8px;\n  padding: 12px;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  border-radius: 10px;\n  background: #1a1d2e;\n  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.45);\n}\n\n._title_1vlbk_97 {\n  margin: 0;\n  font-size: 12px;\n  font-weight: 600;\n  line-height: 1.35;\n  color: rgba(255, 255, 255, 0.78);\n}\n\n._inputWrap_1vlbk_105 {\n  position: relative;\n  display: flex;\n  align-items: center;\n}\n\n._inputWithSuffix_1vlbk_111 {\n  padding-right: 48px;\n}\n\n._suffix_1vlbk_115 {\n  position: absolute;\n  right: 11px;\n  top: 50%;\n  transform: translateY(-50%);\n  pointer-events: none;\n  font-size: 12px;\n  font-weight: 700;\n  letter-spacing: 0.04em;\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._input_1vlbk_105 {\n  width: 100%;\n  box-sizing: border-box;\n  padding: 9px 11px;\n  border: 1px solid rgba(112, 139, 219, 0.28);\n  border-radius: 8px;\n  background: #161925;\n  color: rgba(255, 255, 255, 0.92);\n  font-family: inherit;\n  font-size: 14px;\n  font-weight: 500;\n  transition:\n    border-color 150ms ease,\n    background 150ms ease;\n}\n\n._input_1vlbk_105::placeholder {\n  color: rgba(255, 255, 255, 0.35);\n}\n\n._input_1vlbk_105:hover {\n  border-color: rgba(112, 139, 219, 0.45);\n}\n\n._input_1vlbk_105:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n  border-color: rgba(112, 139, 219, 0.5);\n}\n\n._inputError_1vlbk_157 {\n  border-color: rgba(220, 80, 80, 0.55);\n}\n\n._note_1vlbk_161 {\n  margin: 0;\n  font-size: 11px;\n  line-height: 1.4;\n  color: rgba(255, 255, 255, 0.42);\n}\n\n._error_1vlbk_168 {\n  margin: 0;\n  font-size: 11px;\n  line-height: 1.4;\n  color: #f5a0a0;\n}\n\n._saved_1vlbk_175 {\n  margin: 0;\n  font-size: 11px;\n  font-weight: 600;\n  line-height: 1.4;\n  color: #7fd49a;\n}\n\n._actions_1vlbk_183 {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n}\n\n._save_1vlbk_175 {\n  flex: 1;\n  padding: 8px 12px;\n  border: none;\n  border-radius: 8px;\n  background: linear-gradient(180deg, #708bdb 0%, #3f43cf 100%);\n  color: #fff;\n  font-family: inherit;\n  font-size: 13px;\n  font-weight: 600;\n  cursor: pointer;\n  transition: filter 150ms ease;\n}\n\n._save_1vlbk_175:hover {\n  filter: brightness(1.08);\n}\n\n._save_1vlbk_175:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._clearBtn_1vlbk_212 {\n  padding: 8px 12px;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  border-radius: 8px;\n  background: transparent;\n  color: rgba(255, 255, 255, 0.7);\n  font-family: inherit;\n  font-size: 13px;\n  font-weight: 600;\n  cursor: pointer;\n  transition:\n    border-color 150ms ease,\n    color 150ms ease,\n    background 150ms ease;\n}\n\n._clearBtn_1vlbk_212:hover {\n  border-color: rgba(220, 80, 80, 0.5);\n  background: rgba(220, 80, 80, 0.12);\n  color: #f5b5b5;\n}\n\n._clearBtn_1vlbk_212:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._hint_1vlbk_239 {\n  margin: 0;\n  font-size: 12px;\n  line-height: 1.45;\n  color: rgba(255, 255, 255, 0.55);\n}\n";
  const alertsMenuStyles = "._wrap_1uhwi_1 {\n  position: relative;\n  display: inline-flex;\n  flex-shrink: 0;\n}\n\n._bell_1uhwi_7 {\n  position: relative;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  width: 34px;\n  height: 34px;\n  margin: 0;\n  padding: 0;\n  border: 1px solid rgba(232, 164, 58, 0.45);\n  border-radius: 8px;\n  background: rgba(232, 164, 58, 0.14);\n  color: #f0c050;\n  cursor: pointer;\n  transition:\n    color 150ms ease,\n    border-color 150ms ease,\n    background 150ms ease;\n}\n\n._bell_1uhwi_7:hover {\n  color: #ffd470;\n  border-color: rgba(232, 164, 58, 0.7);\n  background: rgba(232, 164, 58, 0.22);\n}\n\n._bell_1uhwi_7:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._bellOpen_1uhwi_38 {\n  color: #fff;\n  border-color: rgba(112, 139, 219, 0.65);\n  background: rgba(63, 67, 207, 0.35);\n  box-shadow: 0 0 0 1px rgba(112, 139, 219, 0.25);\n}\n\n._bellUrgent_1uhwi_45 {\n  border-color: rgba(232, 164, 58, 0.75);\n  background: rgba(232, 164, 58, 0.24);\n  color: #f0c050;\n}\n\n._badge_1uhwi_51 {\n  position: absolute;\n  top: -6px;\n  right: -6px;\n  min-width: 16px;\n  height: 16px;\n  padding: 0 3px;\n  box-sizing: border-box;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  border-radius: 8px;\n  background: rgba(112, 139, 219, 0.9);\n  color: #fff;\n  font-size: 10px;\n  font-weight: 700;\n  line-height: 1;\n  font-variant-numeric: tabular-nums;\n  box-shadow: 0 0 0 2px #1a1d2e;\n}\n\n._badgeUrgent_1uhwi_72 {\n  background: linear-gradient(#cc7032 0, #b3382c);\n}\n\n._menu_1uhwi_76 {\n  position: absolute;\n  top: calc(100% + 10px);\n  right: 0;\n  z-index: 60;\n  width: 288px;\n  max-width: 86vw;\n  box-sizing: border-box;\n  display: flex;\n  flex-direction: column;\n  gap: 10px;\n  padding: 14px;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  border-radius: 12px;\n  background: #1a1d2e;\n  box-shadow: 0 16px 40px rgba(0, 0, 0, 0.5);\n}\n\n._menuHeader_1uhwi_94 {\n  display: flex;\n  align-items: baseline;\n  justify-content: space-between;\n  gap: 8px;\n}\n\n._menuTitle_1uhwi_101 {\n  font-size: 14px;\n  font-weight: 700;\n  color: #fff;\n}\n\n._menuMatching_1uhwi_107 {\n  font-size: 11px;\n  font-weight: 600;\n  color: #f4b48a;\n}\n\n._empty_1uhwi_113 {\n  margin: 0;\n  font-size: 12px;\n  line-height: 1.5;\n  color: rgba(255, 255, 255, 0.55);\n}\n\n._empty_1uhwi_113 svg {\n  vertical-align: -1px;\n  color: #f0c050;\n}\n\n._list_1uhwi_125 {\n  margin: 0;\n  padding: 0;\n  list-style: none;\n  display: flex;\n  flex-direction: column;\n  gap: 6px;\n}\n\n._row_1uhwi_134 {\n  display: flex;\n  align-items: center;\n  gap: 8px;\n  padding: 6px 8px;\n  border-radius: 8px;\n  background: rgba(112, 139, 219, 0.08);\n}\n\n._rowLabel_1uhwi_143 {\n  flex: 1;\n  min-width: 0;\n  margin: 0;\n  padding: 0;\n  border: none;\n  background: none;\n  font-family: inherit;\n  font-size: 13px;\n  font-weight: 600;\n  color: rgba(255, 255, 255, 0.88);\n  text-align: left;\n  cursor: pointer;\n  /* No overflow:hidden — it clips the offset underline so the dotted link\n     decoration never shows. Labels are short, so plain wrapping is fine. */\n  white-space: nowrap;\n  text-decoration-line: underline;\n  text-decoration-style: dotted;\n  text-decoration-color: rgba(255, 255, 255, 0.65);\n  text-decoration-thickness: 1.5px;\n  text-underline-offset: 3px;\n  transition:\n    color 150ms ease,\n    text-decoration-color 150ms ease,\n    text-decoration-style 150ms ease;\n}\n\n._rowLabel_1uhwi_143:hover {\n  color: #fff;\n  text-decoration-style: solid;\n  text-decoration-color: #fff;\n}\n\n._rowLabel_1uhwi_143:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n  border-radius: 3px;\n}\n\n._rowValue_1uhwi_182 {\n  flex-shrink: 0;\n  font-size: 12px;\n  font-weight: 600;\n  font-variant-numeric: tabular-nums;\n  /* Default to the neutral blue; only matching alerts go gold. */\n  color: rgba(158, 181, 240, 0.85);\n}\n\n._rowValueMatching_1uhwi_191 {\n  color: #f0c050;\n}\n\n._volumeRow_1uhwi_195 {\n  display: flex;\n  align-items: center;\n  gap: 10px;\n  padding-top: 2px;\n}\n\n._volumeLabel_1uhwi_202 {\n  font-size: 12px;\n  font-weight: 600;\n  color: rgba(255, 255, 255, 0.6);\n}\n\n._volumeSlider_1uhwi_208 {\n  flex: 1;\n  min-width: 0;\n  height: 6px;\n  margin: 0;\n  accent-color: #708bdb;\n  cursor: pointer;\n}\n\n._volumeSlider_1uhwi_208:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n\n._volumeValue_1uhwi_222 {\n  flex-shrink: 0;\n  min-width: 2.5rem;\n  font-size: 12px;\n  font-weight: 600;\n  font-variant-numeric: tabular-nums;\n  color: rgba(255, 255, 255, 0.7);\n  text-align: right;\n}\n\n._settingsLink_1uhwi_232 {\n  width: 100%;\n  padding: 9px 12px;\n  border: 1px solid rgba(112, 139, 219, 0.3);\n  border-radius: 8px;\n  background: transparent;\n  color: rgba(200, 216, 255, 0.9);\n  font-family: inherit;\n  font-size: 12px;\n  font-weight: 600;\n  cursor: pointer;\n  transition:\n    border-color 150ms ease,\n    background 150ms ease,\n    color 150ms ease;\n}\n\n._settingsLink_1uhwi_232:hover {\n  border-color: rgba(112, 139, 219, 0.55);\n  background: rgba(112, 139, 219, 0.14);\n  color: #fff;\n}\n\n._settingsLink_1uhwi_232:focus-visible {\n  outline: 2px solid #708bdb;\n  outline-offset: 2px;\n}\n";
  const ptsAmountInputStyles = "._wrapper_8lgpn_1 {\n  position: relative;\n  display: block;\n  width: 100%;\n}\n\n._group_8lgpn_7 {\n  display: flex;\n  align-items: stretch;\n  width: 100%;\n  box-sizing: border-box;\n  border: 1px solid rgba(112, 139, 219, 0.35);\n  border-radius: 6px;\n  background: #1a1d2e;\n  overflow: hidden;\n  transition:\n    border-color 150ms ease,\n    box-shadow 150ms ease;\n}\n\n/* Lives in .wrapper (outside .group's overflow:hidden) so it isn't clipped. */\n._tooltip_8lgpn_22 {\n  position: absolute;\n  bottom: calc(100% + 6px);\n  left: 0;\n  z-index: 20;\n  max-width: 280px;\n  padding: 8px 10px;\n  border-radius: 6px;\n  background: #0d0f18;\n  border: 1px solid rgba(112, 139, 219, 0.4);\n  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.5);\n  color: rgba(255, 255, 255, 0.88);\n  font-size: 11px;\n  font-weight: 500;\n  line-height: 1.5;\n  pointer-events: none;\n}\n\n._tooltipLine_8lgpn_40 {\n  display: block;\n}\n\n._tooltipLine_8lgpn_40 + ._tooltipLine_8lgpn_40 {\n  margin-top: 2px;\n  color: rgba(158, 181, 240, 0.9);\n  font-variant-numeric: tabular-nums;\n}\n\n._group_8lgpn_7:focus-within {\n  border-color: #708bdb;\n  box-shadow: 0 0 0 2px rgba(112, 139, 219, 0.25);\n}\n\n._groupError_8lgpn_55 {\n  border-color: #e85d6a;\n}\n\n._symbol_8lgpn_59 {\n  flex-shrink: 0;\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  min-width: 44px;\n  margin: 0;\n  padding: 0 12px;\n  border: none;\n  border-right: 1px solid rgba(112, 139, 219, 0.25);\n  background: rgba(112, 139, 219, 0.12);\n  color: rgba(158, 181, 240, 0.9);\n  font-family: inherit;\n  font-size: 12px;\n  font-weight: 700;\n  letter-spacing: 0.04em;\n  text-transform: uppercase;\n  cursor: pointer;\n  transition:\n    background 150ms ease,\n    color 150ms ease;\n}\n\n._symbol_8lgpn_59:hover:not(:disabled) {\n  background: rgba(112, 139, 219, 0.24);\n  color: #c8d8ff;\n}\n\n._symbol_8lgpn_59:active:not(:disabled) {\n  background: rgba(112, 139, 219, 0.32);\n}\n\n._symbol_8lgpn_59:disabled {\n  cursor: default;\n  opacity: 0.5;\n}\n\n._input_8lgpn_96 {\n  flex: 1;\n  min-width: 0;\n  box-sizing: border-box;\n  padding: 10px 12px;\n  border: none;\n  background: transparent;\n  color: #fff;\n  font-family: inherit;\n  font-size: 15px;\n  font-variant-numeric: tabular-nums;\n}\n\n._input_8lgpn_96:focus {\n  outline: none;\n}\n\n._input_8lgpn_96:disabled {\n  color: rgba(255, 255, 255, 0.45);\n}\n\n._postfix_8lgpn_117 {\n  flex-shrink: 0;\n  display: inline-flex;\n  align-items: center;\n  padding: 0 12px;\n  pointer-events: none;\n  font-size: 13px;\n  font-weight: 600;\n  color: rgba(255, 255, 255, 0.45);\n  font-variant-numeric: tabular-nums;\n  white-space: nowrap;\n}\n";
  function mountApp() {
    initReferencesScraper();
    initBountyRevealScraper();
    initPresencePing();
    const existing = document.getElementById(CONTENT_HOST_ID) ?? document.getElementById(LEGACY_CONTENT_HOST_ID);
    if (existing == null ? void 0 : existing.shadowRoot) return;
    let host = existing;
    if (!host) {
      host = document.createElement("div");
      document.documentElement.appendChild(host);
    }
    host.id = CONTENT_HOST_ID;
    const shadow = host.attachShadow({ mode: "open" });
    injectStyles(shadow, [
      appStyles,
      sidebarStyles,
      modeSwitchStyles,
      contractModalStyles,
      apiKeySetupStyles,
      buyingPanelStyles,
      activeContractStyles,
      payoutValueStyles,
      copyIdButtonStyles,
      buyersPanelStyles,
      insurancePolicyModalStyles,
      serviceBentoCardStyles,
      serviceBentoThemeStyles,
      serviceCategoryModalStyles,
      bountyOrderModalStyles,
      tornPrimaryValueStyles,
      activeBountyOrderCardStyles,
      activeInsuranceCardStyles,
      insuranceClaimModalStyles,
      contractTypePickerStyles,
      settingsPanelStyles,
      animatedListStyles,
      inProgressModalStyles,
      buyerOrderProgressModalStyles,
      referralsModalStyles,
      productivityBoostOrderModalStyles,
      productivityBoostCompanyLinkStyles,
      activeProductivityBoostCardStyles,
      embargoTargetLinkStyles,
      flightDelayTargetLinkStyles,
      simpleServiceTargetLinkStyles,
      referencesReportModalStyles,
      alertBellPopoverStyles,
      alertsMenuStyles,
      ptsAmountInputStyles
    ]);
    const mountEl = document.createElement("div");
    mountEl.dataset.tlmMount = "";
    shadow.appendChild(mountEl);
    clientExports.createRoot(mountEl).render(/* @__PURE__ */ jsxRuntimeExports.jsx(App, {}));
  }
  configurePlatformRuntime(userscriptRuntime);
  mountApp();
})(supabase);